【问题标题】:Cannot pass guid as uniqueidentifier to storedprocedure无法将 guid 作为唯一标识符传递给存储过程
【发布时间】:2011-05-30 09:39:02
【问题描述】:

我有一个将唯一标识符作为参数的存储过程。

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

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 是一个具有正确值的 Guid 对象,但我仍然遇到同样的异常。

这里出了什么问题?

解决方案:问题出在 return 语句中。 sp 返回一个不能转换为 bool 的 int 值:

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

【问题讨论】:

  • 为什么你的代码中有@key 和@activationkey?你能展示一下 sp 吗?
  • 您是否检查过 guid 是否从您的密钥字符串中正确实例化?键不为空吗?
  • 而不是将 SqlDbType.UniqueIdentifier 作为字符串并检查,我认为它应该可以工作
  • 请添加您的存储过程代码,它将提供更多信息

标签: c# sql-server uniqueidentifier


【解决方案1】:

ExecuteScalar() 不返回 bool 类型:

类型:System.Object

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

另外,您使用名称“@key”创建参数,然后在此行中使用不同的名称:

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

【讨论】:

    【解决方案2】:

    我认为您的意思是 @key 而不是 @activationkey。然后你可以像这样添加一个参数:

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

    【讨论】:

      【解决方案3】:

      'Specified cast is not valid'的意思是你选错了,这是你唯一这样做的地方:

      return (bool)command.ExecuteScalar();
      

      检查这个值。它是 DBNull 或其他数据类型。尝试调试它,找出数据类型。

      【讨论】:

        【解决方案4】:

        您指定一个参数"@key",作为唯一标识符类型,

        那么您将guid 设置为参数"@activationkey",该参数尚未声明。

        我认为您不应该将值设置为"@activationkey",而是应该是key

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-21
          • 1970-01-01
          • 2014-08-29
          • 1970-01-01
          • 2021-04-28
          相关资源
          最近更新 更多