0

是否可以编辑从 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);
      }
   }
}
4

1 回答 1

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 ();
  }
于 2010-10-15T19:09:02.403 回答