简体   繁体   中英

JSON string output parameter from SQL Server stored procedure works in SSMS but produces empty value in C# client

In my stored procedure, I've declared an OUTPUT parameter called @Stats :

@Stats nvarchar(max) OUTPUT

At the end of my stored procedure, I assign the results of a JSON query to the output parameter:

SELECT @Stats = (SELECT * FROM JsonStats FOR JSON AUTO)

If I execute the stored procedure in SSMS, I get the JSON data back from @Stats as expected:

DECLARE @Param1 nvarchar(max) = '...'
DECLARE @Stats nvarchar(max)

EXEC MySP @Param1, @Stats OUTPUT

SELECT @Stats

However, when I execute the stored procedure from C# code, I get an empty string back:

SqlCommand cmd = new SqlCommand("MySP", conn)
        {
            CommandType = CommandType.StoredProcedure
        };

var inputParam = new SqlParameter("@Param1", invoiceKeyListJson);
cmd.Parameters.Add(inputParam);

var outputParam = new SqlParameter("@Stats", SqlDbType.NVarChar, -1);
outputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParam);

cmd.ExecuteNonQuery();

string statsJson = outputParam.Value.ToString();

After running the above code, statsJson is empty. The weird thing is, if I hard code the assignment of @Stats to an arbitrary string in the stored procedure, statsJson is assigned that value.

Why the inconsistency in results between SSMS and C#? What do I need to do to get the JSON data back in C#?

I resolved this by changing

SELECT @Stats = (SELECT * FROM JsonStats FOR JSON AUTO)

to:

SELECT @Stats = CAST((SELECT * FROM JsonStats FOR JSON AUTO) AS nvarchar(max))

(explicitly casting to nvarchar(max) ).

您必须像这样设置outputParam的大小:

var outputParam = new SqlParameter("@Stats", SqlDbType.NVarChar, 100000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM