Creating a managed stored procedure that uses ADO.NET using only the SDK
If you don't have Visual Studio 2005 handy, or you'd like to see how things work the first time before letting Visual Studio do it for you, here is how to create a SQLCLR stored procedure by hand.
First, you need the code for the stored procedure. Let's say you want to do the same as in the Visual Studio example: connect to another SQL Server, obtain some information based on input data, and process the results.
C#
using System.Data;
using System.Data.SqlClient;
public class SP {
public static void SampleSP() {
// as usual, connection strings shouldn't
// be hardcoded for production code
using(SqlConnection conn =
new SqlConnection("server=MyServer;
database=AdventureWorks;
" + "user id=MyUser;
password=MyPassword")) {
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT Name, GroupName FROM
HumanResources.Department", conn);
SqlDataReader r = cmd.ExecuteReader();
while(r.Read()) {
// consume the data from the reader
// and perform some processing
}
}
}
}
Visual Basic .NET
Imports System.Data
Imports System.Data.SqlClient
Public Class SP
Public Shared Sub SampleSP()
Dim cmd As SqlCommand
Dim r As SqlDataReader
' as usual, connection strings shouldn't
' be hardcoded for production code
Using conn As New SqlConnection( _
"server=MyServer;
database=AdventureWorks;
user id=MyUser; password=MyPassword")
conn.Open()
cmd = New SqlCommand( _
"SELECT Name, GroupName FROM
HumanResources.Department", conn)
r = cmd.ExecuteReader()
Do While r.Read()
' consume the data from the reader
' and perform some processing
Loop
End Using
End Sub
End Class
Again, nothing different from old fashioned ADO.NET :)
Now you need to compile your code to produce a DLL assembly containing the stored procedure. The following command will do it (assuming that you called your file myprocs.cs/myprocs.vb and the .NET Framework 2.0 is in your path):
C#
csc /t:library myprocs.cs
VB
vbc /t:library myprocs.vb