如何从 CLR 存储过程中获取结果

How to get a result from CLR stored procedure

我在 c# 中有一个 CLR 存储过程,类似于

public partial class StoredProcedures
{  
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void DecimalToWords (decimal sum)
    {
        SqlPipe pipe = SqlContext.Pipe;
        SqlMetaData[] cols = new SqlMetaData[1];
        cols[0] = new SqlMetaData("Sum", SqlDbType.NVarChar, 1024);
        SqlDataRecord rec = new SqlDataRecord(cols);

        string result = sum.ToString();

        pipe.SendResultsStart(rec);

        rec.SetSqlString(0, new SqlString(result));
        rec.SetSqlString(0, new SqlString("End of result"));
        pipe.SendResultsEnd();
    }
}

我试过用

调用它
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[DecimalToWords]
        @sum = 10002

SELECT  'Return Value' = @return_value

GO

此 return @return_value 为 0,实际过程的结果为空 table,具有单个列名 'sum',我认为这意味着实际程序有效。

我也试过用

调用它
DECLARE @return_value int
Declare @tep_table table
(
  Sum varchar(1024)
)

Insert into @tep_table
EXEC    @return_value = [dbo].[DecimalToWords]
        @sum = 123

Select * From @tep_table

这也是 return 一个空 table。

如何从我的程序中获取 'result' 字符串的值?我的程序代码有问题吗?我是不是调用错了程序?

你错过了SendResultsRow:

        pipe.SendResultsStart(rec);

        rec.SetSqlString(0, new SqlString(result));
        rec.SetSqlString(0, new SqlString("End of result"));
        pipe.SendResultsRow(rec);
        pipe.SendResultsEnd();

您的示例中并不需要 Start/Row/End,但我认为这只是一个示例。消费结果时,只需要执行过程,结果集就会发送给客户端。