在.NET sproc中使用SQLContext.Pipe.Send()之前更改结果

时间:2010-10-15 18:58:20

标签: c# .net sql-server-2005 stored-procedures sqlconnection

是否可以编辑从command.ExecuteReader返回的数据,然后将其返回给SqlContext.Pipe.Send()?是否有任何可预见的问题(我必须将光标重置为开头)?

我有一个.NET存储过程,它将查询像这样的表

(来自MSDN的代码)

public class StoredProcedures 
{
   /// <summary>
   /// Execute a command and send the resulting reader to the client
   /// </summary>
   [Microsoft.SqlServer.Server.SqlProcedure]
   public static void SendReaderToClient()
   {
      using(SqlConnection connection = new SqlConnection("context connection=true")) 
      {
         connection.Open();
         SqlCommand command = new SqlCommand("select FirstName,LastName, PictureURL from myTable", connection);
         SqlDataReader r = command.ExecuteReader();
         //QUESTION: Can I modify "r" here, and return it below?
         SqlContext.Pipe.Send(r);
      }
   }
}

1 个答案:

答案 0 :(得分:3)

您可以使用SendResultStart描述自己的结果集,然后使用SendResultsRow发送每一行:

  using(SqlConnection connection = new SqlConnection("context connection=true")) 
  {
     // Create the record and specify the metadata for the columns.
     // This record describes a result with two columns:
     //  Name NVARCHAR(4000)
     //  URL VARCHAR(4000)
     //
     SqlDataRecord record = new SqlDataRecord(
       new SqlMetaData("Name", SqlDbType.NVarChar, 4000),
       new SqlMetaData("URL", SqlDbType.VarChar, 4000),
       ...);

     // Mark the begining of the result-set.
     SqlContext.Pipe.SendResultsStart(record);

     connection.Open();
     SqlCommand command = new SqlCommand("select Name, Picture from myTable", connection);
     using (SqlDataReader rdr = command.ExecuteReader())
     {
        while(rdr.Read ())
        {
            // Transform the current row from rdr into the target record
            string nameDb = rdr.GetString(0);
            string urlDb = rdr.GetString(1);

            // do the transformations:
            string nameResult = String.Format("<h2>{0}</h2>", nameDb);
            string awt = ComputeTheAWT(urlDb);
            string urlResult = FormatURL (urlDb, awt);

            // Assign the record properties
            record.SetString(0, nameResult);
            record.SetString(1, urlResult);

            // send the record
            SqlContext.Pipe.SendResultsRow(record);
        }
     }
     SqlContext.Pipe.SendResultsEnd ();
  }