Get Output Parameter Value in C#

Dio*_*des 0 c# sql sql-server parameters stored-procedures

I have a stored procedure with an OUTPUT parameter:

CREATE PROCEDURE [dbo].[myStoredProcedure]
    (@myValue NVARCHAR(100) OUTPUT)
AS
BEGIN
    SET @myValue = (SELECT myValue FROM myTable WHERE something = 1)
    SElECT @myValue;
END
Run Code Online (Sandbox Code Playgroud)

My C# class:

public string getOutPut()
{
    string shortFooter;
    string sql = "myStoredProcedure";
    string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    using (SqlConnection DBConn = new SqlConnection(connStr))
    {
        using (SqlCommand DBCmd = new SqlCommand(sql, DBConn))
        {
            try
            {
                DBConn.Open();

                DBCmd.CommandType = CommandType.StoredProcedure;
                SqlParameter newSqlParam = new SqlParameter();
                newSqlParam.ParameterName = "@myValue";
                newSqlParam.SqlDbType = SqlDbType.NVarChar;
                newSqlParam.Direction = ParameterDirection.Output;
                DBCmd.Parameters.Add(newSqlParam);

                DBCmd.ExecuteNonQuery();
                shortFooter = DBCmd.Parameters["@myValue"].Value.ToString();
            }
            catch (Exception ex)
            {
                string blah = ex.ToString();
                shortFooter = "";
            }
        }
    }

    return shortFooter;
}
Run Code Online (Sandbox Code Playgroud)

This is the exception that I'm getting:

System.InvalidOperationException: String[0]: the Size property has an invalid size of 0.

我不明白的是,我之前使用过这段代码,除了在存储过程中我IDENTITY()在数据库中创建新记录时获取输出的值,因此类中的参数类型为INT . 但在概念上它应该是相同的,但我想我错了,只是不知道为什么。

我错过了什么?

谢谢!!

Gra*_*ICA 5

您需要指定保存输出值所需的大小。从MSDN

对于具有可变长度类型(例如 nvarchar)的输出参数,参数的大小定义了保存输出参数的缓冲区的大小。

Size在代码中设置输出参数的 以匹配存储过程中的内容:

newSqlParam.Size = 100;
Run Code Online (Sandbox Code Playgroud)

默认值为 0,这是导致异常的原因。