International Developer Logo Last Updated 27.08.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 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 computation with it
  }
}



Visual Basic .NET
Dim cmd as SqlCommand
Dim r as SqlDataReader
? 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 computation with it
  Loop
End Using


This sample uses the System.Data.SqlClient provider to connect to SQL Server. Note that if this code runs inside SQLCLR, it would be connecting from the SQL Server that hosts it to another SQL Server. You can also connect to different data sources. For example, you can use the System.Data.OracleClient provider to connect to an Oracle server directly from inside SQL Server.

For the most part, there are no major differences using ADO.NET from within SQLCLR. However, there is one scenario that needs a little bit more attention: what if you want to connect to the same server your code is running in to retrieve/alter data? See The Context Connection section to see how ADO.NET addresses that.
Before delving into further detail, I'd like to go through the basic steps to run code inside SQLCLR. If you already have experience creating SQLCLR stored procedures, you'll probably want to skip this section.




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

HAVE YOUR SAY
This article is rated  Rate this article