Following along with an example I found on the internet, I wrote the following C# code that implements a CLR stored procedure in MS SQL Server 2008:
public class Class1
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void CountStringLength(string inputString)
{
SqlContext.Pipe.Send(inputString.Length.ToString());
}
}
This procedure takes a string as a parameter and outputs the number of characters in the string.
I have been working on some code that retrieves data from SQL; there's nothing special about the way the data is retrieved: it makes a connection to the SQL server, selects the data, and then closes the connection. I want to make this code run inside a stored procedure or trigger on my SQL server.
I suppose that I could make the code run exactly the same as the existing SQL code: make a connection to the SQL server, select the data, and then close the connection. However, this doesn't make sense once the code is running on the SQL server itself! Why would I want code that runs on the SQL server make the server connect to itself?!?!
Is there a best practice for what I'm trying to do? Can I select rows in my code using the same connection that is used to execute the stored procedure?
I found the answer explained here: http://technet.microsoft.com/en-us/library/ms131053.aspx
The connection that the CLR procedure runs from is called the "Context Connection" and it is used like this:
using(SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
// Use the connection
}
I wonder why you have to "open" the connection? I would think that the connection is already open since it is executing the procedure that is running.
Also closely related: http://msdn.microsoft.com/en-us/library/938d9dz2(v=vs.90).aspx