调用存储过程返回30个字符中的1个

时间:2015-11-30 16:41:34

标签: c# sql-server stored-procedures

我以编程方式调用SQL Server存储过程,该过程应返回30个随机字符。相反,它只返回1个字符。我错过了什么?

当我在SQL Server中执行它时,存储过程正常工作,但在C#中,它无法正常工作。

var messageId = "";

try
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
    {
        conn.Open();

        using (SqlCommand command = new SqlCommand("GenerateMessageId", conn))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@msgid", messageId);
            command.Parameters[0].Direction = ParameterDirection.Output;

            command.ExecuteNonQuery();
            messageId = (string)command.Parameters[0].Value;
        }
    }
}

存储过程:

ALTER PROCEDURE [dbo].[GenerateMessageId]
    @msgid varchar(30) OUT
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    EXEC dbo.GenerateRandomString 1, 1, 1, null, 30, @msgid OUT
END

1 个答案:

答案 0 :(得分:3)

尝试添加:

command.Parameters[0].Size = 30;

command.Parameters.Add("@msgid", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output;

或使用明确声明:

 SqlParameter msgid= new SqlParameter {
    ParameterName = "@msgid",
    IsNullable    = true,
    Direction     = ParameterDirection.Output,
    DbType        = DbType.String,
    Size          = 30,
    Value         = messageId,
    } ;
  command.Parameters.Add(msgid);