SCOPE_IDENTITY 似乎不适用于参数化查询

SCOPE_IDENTITY does not seem to work with parameterized queries(SCOPE_IDENTITY 似乎不适用于参数化查询)
本文介绍了SCOPE_IDENTITY 似乎不适用于参数化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个带有标识列的表,我想在插入后获取该列的值.以下不使用参数的代码运行良好:

I have a table with an identity column whose value I would like to get after an INSERT. The following code, which does not use parameters, is working perfectly:

string query = "INSERT INTO aTable ([aColumn]) VALUES (42)";
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteNonQuery();

query = "SELECT CAST(SCOPE_IDENTITY() AS bigint)";
command = new SqlCommand(query, connection);
object identity = command.ExecuteScalar();

如果我将上述代码的 INSERT 部分更改为使用参数化查询,ExecuteScalar() 会突然返回一个 System.DBNull 值.这是参数化查询代码的样子:

If I change the INSERT part of the above code to use a parameterized query, ExecuteScalar() suddenly returns a System.DBNull value. This is how the parameterized query code looks like:

string query = "INSERT INTO aTable ([aColumn]) VALUES (@aColumn)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@aColumn", 42);
command.ExecuteNonQuery();

我尝试更改 SCOPE_IDENTITY 代码,以便它使用输出参数并调用 ExecuteNonQuery(),但我仍然在 out 参数中得到空值.我还尝试在两个不同版本的 SQL Server(2012 和 2008,都为 Express 版)上运行代码,结果相同.

I have tried to change the SCOPE_IDENTITY code so that it uses an output parameter and invokes ExecuteNonQuery(), but I still get a null value in the out parameter. I have also tried running the code against two different versions of SQL Server (2012 and 2008, both Express Edition), again with the same result.

知道我在这里做错了什么吗?

Any ideas what I am doing wrong here?

推荐答案

尝试将 INSERT 和 SELECT 合并为一个语句

Try combining your INSERT and SELECT into one statement

string query = "INSERT INTO aTable ([aColumn]) VALUES (@aColumn);SELECT CAST(SCOPE_IDENTITY() AS bigint)"; 
SqlCommand command = new SqlCommand(query, connection); 
command.Parameters.AddWithValue("@aColumn", 42); 
object identity = command.ExecuteScalar(); 

这篇关于SCOPE_IDENTITY 似乎不适用于参数化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Simulating MySQL#39;s ORDER BY FIELD() in Postgresql(在 Postgresql 中模拟 MySQL 的 ORDER BY FIELD())
Using MySQL query to traverse rows to make a recursive tree(使用MySQL查询遍历行制作递归树)
add column to mysql table if it does not exist(如果不存在,则将列添加到 mysql 表)
MIN/MAX vs ORDER BY and LIMIT(MIN/MAX 与 ORDER BY 和 LIMIT)
How can I merge two MySQL tables?(如何合并两个 MySQL 表?)
Cannot add or update a child row: a foreign key constraint fails(无法添加或更新子行:外键约束失败)