Tomas
Tomas

Reputation: 191

How to get a result from CLR stored procedure

I have a CLR stored procedure in c# that goes something like

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();
    }
}

I tried calling it by

GO

DECLARE @return_value int

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

SELECT  'Return Value' = @return_value

GO

This return @return_value as 0 and the result of the actual procedure as an empty table with a single column name 'sum' which I assume means that the actual procedure works.

I also tried calling it by

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

This also returns an empty table.

How would I get the value of 'result' string from my procedure? Is there a problem with my procedure code? Am I calling the procedure wrong?

Upvotes: 1

Views: 1119

Answers (1)

Remus Rusanu
Remus Rusanu

Reputation: 294247

You are missing SendResultsRow:

        pipe.SendResultsStart(rec);

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

You don't really need the Start/Row/End in your example, but I assume is just an example. When consuming the result, just execute the procedure and the result set will be sent to the client.

Upvotes: 3

Related Questions