C#
using(SqlConnection c = new SqlConnection
("context connection=true")) {
c.Open();
// do something with the connection
}
Visual Basic .NET
Using c as new SqlConnection("context
connection=true")
c.Open()
' do something with the connection
End Using
In order to see whether your code is actually running in the same connection as the caller, you can do the following experiment: use a SqlConnection object and compare the SPID (the SQL Server session identifier) as seen from the caller and from within the connection. The code for the procedure looks like this:
C#
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.
SqlProcedure()]
public static void SampleSP(
string connstring, out int spid) {
using (SqlConnection conn =
new SqlConnection(connstring)) {
conn.Open();
SqlCommand cmd = new SqlCommand
("SELECT @@SPID", conn);
spid = (int)cmd.ExecuteScalar();
}
}
}
Visual Basic .NET
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.SqlServer.Server
Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub SampleSP(ByVal
connstring As String, ByRef spid
As Integer)
Using conn As New SqlConnection
(connstring)
conn.Open()
Dim cmd As New SqlCommand
("SELECT @@SPID", conn)
spid = CType(cmd.ExecuteScalar(),
Integer)
End Using
End Sub
End Class