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

The example above shows how to send the results from a SQL query back to the client. However, it's very likely that you'll also have stored procedures that produce their own data (e.g., by performing some computation locally or by invoking a Web service) and you'll want to return that data to the client as a result set. That's also possible using SQLCLR. Here is a trivial example:

C#
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures {
   [Microsoft.SqlServer.Server.
   SqlProcedure()]
  public static void SampleSP() {
  // simply produce a 10-row result-set with 2 columns,
// an int and a string first, create the record and
// specify the metadata for the results
   SqlDataRecord rec = new SqlDataRecord(
    new SqlMetaData("col1", SqlDbType.
      NVarChar, 100),
    new SqlMetaData("col2", SqlDbType.
      Int));
  // start a new result-set
  SqlContext.Pipe.SendResultsStart(rec);
  // send rows
  for(int i = 0; i < 10; i++) {
  // set values each column for this row
  // This data would presumably come from a more
// "interesting" computation
   rec.SetString(0, "row " +
     i.ToString());
   rec.SetInt32(1, i);
   SqlContext.Pipe.SendResultsRow(rec);
  }
  // complete the result-set
  SqlContext.Pipe.SendResultsEnd();
 }
}
Visual Basic .NET
Imports System.Data
Imports System.Data.SqlClient
Imports System.Transactions
Imports Microsoft.SqlServer.Server
Partial Public Class StoredProcedures
    <Microsoft.SqlServer.Server.
    SqlProcedure()> _
  Public Shared Sub SampleSP()
   ' simply produce a 10-row result-set with 2 columns,
' an int and a string first, create the record and
' specify the metadata for the results
   Dim rec As New SqlDataRecord( _
    New SqlMetaData("col1", SqlDbType.
     NVarChar, 100), _
    New SqlMetaData("col2", SqlDbType.
     Int))
' start a new result-set
   SqlContext.Pipe.SendResultsStart(rec)
' send rows
   Dim i As Integer
   For i = 0 To 9
' set values for each column for this row. This data
' would presumably come from a more "interesting" computation
    rec.SetString(0, "row " &
      i.ToString())
    rec.SetInt32(1, i)
    SqlContext.Pipe.SendResultsRow(rec)
   Next
   ' complete the result-set
   SqlContext.Pipe.SendResultsEnd()
  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