无法将guid作为uniqueidentifier传递给存储过程

时间:2011-05-30 09:39:02

标签: c# sql-server uniqueidentifier

我有一个存储过程,它将uniqueidentifier作为参数。

它应该像这样工作(我没有写这个):

SqlCommand command = new SqlCommand("[CheckActivation]", Conn)
{
    CommandType = CommandType.StoredProcedure
};
command.Parameters.AddWithValue("@key", key);
return (bool)command.ExecuteScalar();

其中 key 是一个字符串,但它没有。我总是得到'指定的演员阵容无效'例外。

所以我把它改写成:

Guid guid = new Guid(key);
using (var command = Conn.CreateCommand())
{
    command.CommandText = "[CheckActivation]";
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@key", SqlDbType.UniqueIdentifier);
    command.Parameters["@key"].Value = guid;

    return (bool)command.ExecuteScalar();
}

guid是一个带有correnct值的Guid对象,但我仍然得到相同的异常。

这里出了什么问题?

解决方案:问题是返回语句中的强制转换。 sp返回一个无法转换为bool的int值:

return((int)command.ExecuteScalar()== 1);

4 个答案:

答案 0 :(得分:1)

ExecuteScalar()不返回bool类型:

  

类型:System.Object

     

第一行的第一列   结果集或空引用   (如果没有Visual Basic中的任何内容)   结果集为空。返回最大值   2033个字符。

此外,您使用名称“@key”创建参数,然后在此行中使用其他名称:

 command.Parameters["@activationkey"].Value = guid;

答案 1 :(得分:1)

我认为您的意思是@key而不是@activationkey。然后你可以添加如下参数:

command.Parameters.Add(new SqlParameter 
  {
     ParameterName = "@key",
     SqlDbType = SqlDbType.UniqueIdentifier,
     Value = new Guid(key)
  });

答案 2 :(得分:0)

您可以将参数"@key"指定为唯一标识符类型

然后您将guid设置为尚未声明的参数"@activationkey"

我认为你不应该将价值设定为"@activationkey",而应该key

command.Parameters["@key"].Value = guid;

答案 3 :(得分:0)

'指定演员表无效'表示您输错了,这是您唯一这样做的地方:

return (bool)command.ExecuteScalar();

检查此值。它是DBNull还是其他数据类型。尝试调试它,找出数据类型。