International Developer Logo Last Updated 25.07.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Managed data access inside SQL Server with ADO.NET and SQLCLR


Pablo Castro   13.02.06

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




   Previous Page  1 2 3 4 5 6 7 8 9 10 ... Next Page   

HAVE YOUR SAY
This article is rated  Rate this article