After compiling and deploying this in SQL Server, you can try it out:
-- Print the SPID as seen by this connection
PRINT @@SPID
-- Now call the stored proc and see what SPID
-- we get for a regular connection
DECLARE @id INT
EXEC SampleSP 'server=.;user id=MyUser;
password=MyPassword',
@id OUTPUT
PRINT @id
-- Call the stored proc again,
-- but now use the context connection
EXEC SampleSP 'context connection=true', @id OUTPUT
PRINT @id
You'll see that the first and last SPID will match, because they're effectively the same connection. The second SPID is different because a second connection (which is a completely new connection) to the server was established.
Using ADO.NET in different SQLCLR objects
The "context" object
As you'll see in the following sections that cover different SQLCLR objects, each one of them will execute in a given server "context." The context represents the environment where the SQLCLR code was activated, and allows code running inside SQLCLR to access appropriate run-time information based on what kind of SQLCLR object it is.
The top-level object that surfaces the context is the SqlContext class that's defined in the Microsoft.SqlServer.Server namespace.
Another object that's available most of the time is the pipe object, which represents the connection to the client. For example, in T-SQL you can use the PRINT statement to send a message back to the client (if the client is SqlClient, it will show up as a SqlConnection.InfoMessage event). You can do the same in SQLCLR by using the SqlPipe object:
C#
SqlContext.Pipe.Send("Hello, World! (from SQLCLR)");
Visual Basic .NET
SqlContext.Pipe.Send("Hello, World! (from SQLCLR)")