检索 scope_identity 时出现特定的转换无效。

11

我遇到了“无法进行特定转换”的异常,以下是代码:

con.Open();
string insertQuery = @"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";

SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();

你尝试过将其拆分为两个SqlCommand对象吗?每个查询一个? - luke
1
你应该意识到你正在执行两次 SQL,因此你会插入两条记录。只需运行 ExecuteScalar 方法即可。 - Anthony Pegram
4个回答

25

为了保证完整性,你的代码存在三个问题:

1)你通过调用ExecuteNonQueryExecuteScalar两次执行了查询。因此,每次该函数运行时,都会向表中插入两条记录。虽然你的SQL语句是两条不同的语句,但它们将一起运行,因此你只需要调用ExecuteScalar

2)Scope_Identity() 返回一个十进制数。你可以在查询结果上使用Convert.ToInt32,或者将返回值转换为十进制数再转换为整数。

3)确保将连接和命令对象包装在using语句中,以便正确处置它们。

using (SqlConnection connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        connection.Open();
        int tenderId = (int)(decimal)command.ExecuteScalar();
    }
}

5

试试这个:

con.Open();
string insertQuery = @"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";

SqlCommand cmd = new SqlCommand(insertQuery, con);
tenderId = Convert.ToInt32(cmd.ExecuteScalar());

编辑

正如正确指出的那样,scope_identity()返回一个数字(38,0):

tenderId = Convert.ToInt32(cmd.ExecuteScalar());

注意:您仍需删除以下内容:-

cmd.ExecuteNonQuery();

4
Scope_Identity()返回一个十进制数。直接转换将不起作用,但是可以使用双重转换(int)(decimal)cmd.ExecuteScalar()或者简单地使用Convert.ToInt32 - Anthony Pegram
@安东尼,是的,你说得对,我已经很久没有使用这种类型的代码了。 - Rippo

2

首先请测试以下内容:

object id = cmd.ExcuteScalar()

设置断点并查看 id 的类型。它很可能是一个 Decimal 类型的变量,因此不能直接强制转换为 int


不是ID列有问题,而是Scope_Identity()的返回值有问题。但你说的小数部分没错。 - Anthony Pegram

1

需要使用 Convert.ToInt32(cmd.ExecuteScalar());


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接