检索scope_identity时,特定强制转换无效
我得到例外:“具体演员无效”,这里是代码
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();
为了完整性,您的代码示例有三个问题。
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(); } }
试试这个:-
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();
首先测试以下内容:
object id = cmd.ExcuteScalar()
设置一个断点并查看id
的类型。 它可能是一个Decimal
,不能直接转换为int
。
它需要Convert.ToInt32(cmd.ExecuteScalar());