检索scope_identity时,特定强制转换无效

cou*_*011 9 c# sql asp.net ado.net

我得到例外:"具体演员无效",这里是代码

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();
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 22

为了完整性,您的代码示例有三个问题.

1)您正在通过调用ExecuteNonQuery和执行两次查询ExecuteScalar.因此,每次运行此函数时,您将在表中插入两条记录.您的SQL虽然是两个不同的语句,但它们将一起运行,因此您只需要调用它ExecuteScalar.

2)Scope_Identity() 返回小数.您既可以使用Convert.ToInt32查询结果,也可以将返回值转换为decimal,然后转换为int.

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

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


Rip*_*ppo 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());
Run Code Online (Sandbox Code Playgroud)

编辑

它应该是这样,因为正确指出scope_identity()返回一个数字(38,0): -

tenderId = Convert.ToInt32(cmd.ExecuteScalar());
Run Code Online (Sandbox Code Playgroud)

注意:您仍然需要删除: -

cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

  • `Scope_Identity()`返回一个小数.直接强制转换不起作用,但双重强制转换将是`(int)(十进制)cmd.ExecuteScalar()`或简单地使用`Convert.ToInt32`. (4认同)