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 System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures {
  [Microsoft.SqlServer.Server.
  SqlProcedure()]
  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
Imports Microsoft.SqlServer.Server
Partial Public Class StoredProcedures
  <Microsoft.SqlServer.Server.SqlProcedure()> _
  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

  • Deploy your assembly. Now you need to deploy your stored procedure in SQL Server. Visual Studio makes it trivial to deploy the assembly to SQL Server and take the appropriate steps to register each of the objects in the assembly with the server. After building the project, on the Build menu, choose Deploy Solution. Visual Studio will connect to SQL Server, drop previous versions of the assembly if needed, send the new assembly to the server and register it, and then register the stored procedure that you added to the assembly.
  • Try it out. You can even customize the "test.sql" file that's generated under the "Test Scripts" project folder to exercise the stored procedure you're working on so Visual Studio will execute it when you press Ctrl+F5, or just press F5. (Yes, F5 will start the debugger, and you can debug code inside SQLCLR - both T-SQL and CLR code - isn't that cool?)



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

    HAVE YOUR SAY
    This article is rated  Rate this article