T-SQL:将新的 INSERT 标识返回给 C#
我使用存储过程将值放入 SQL Server。该过程将向所添加的行添加一个 ID。我需要将此 ID 返回到我的代码中。
目前我可以在 Visual Studio 的 OUTPUT 窗口中看到输出 id,但似乎无法在我的代码中捕获它。以下是该过程的摘要版本:
SQL:
CREATE PROCEDURE dbo.DoSomething
(
@var1 INT = NULL,
@var2 INT = NULL,
@var3 DATE = NULL
)
AS
BEGIN
INSERT INTO atable
(
vara,
varb,
varc
)
VALUES
(
@var1,
@var2,
@var3
)
RETURN SCOPE_IDENTITY()
END
C#:
int result = 0;
/// create command
SqlCommand cmd = new SqlCommand("DoSomething", this.OpenSqlConnection());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@var1", thing.value1);
cmd.Parameters.AddWithValue("@var2", thing.value2);
cmd.Parameters.AddWithValue("@var3", thing.value3);
/// send data to db
result = (int)cmd.ExecuteScalar();
因此我收到错误:未将对象引用设置为对象的实例。< /strong> 当它到达 (int)cmd.ExecuteScalar() 时。
有什么想法吗?
i'm putting values into SQL Server using a Stored Procedure. The Procedure will add an ID to the row that is added. I need to get this ID back to my code.
Currently I can get the I see the output id in the OUTPUT window of Visual Studio, but can't seem to capture it in my code. Here is a summarized version of the proc:
SQL:
CREATE PROCEDURE dbo.DoSomething
(
@var1 INT = NULL,
@var2 INT = NULL,
@var3 DATE = NULL
)
AS
BEGIN
INSERT INTO atable
(
vara,
varb,
varc
)
VALUES
(
@var1,
@var2,
@var3
)
RETURN SCOPE_IDENTITY()
END
C#:
int result = 0;
/// create command
SqlCommand cmd = new SqlCommand("DoSomething", this.OpenSqlConnection());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@var1", thing.value1);
cmd.Parameters.AddWithValue("@var2", thing.value2);
cmd.Parameters.AddWithValue("@var3", thing.value3);
/// send data to db
result = (int)cmd.ExecuteScalar();
So I'm getting an error: Object reference not set to an instance of an object. when it gets to the (int)cmd.ExecuteScalar().
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
RETURN 值实际上作为特殊的 OUTPUT 参数返回。 SELECT 给出 ExecuteScalar 的结果集。
您可以使用 OUTPUT 子句代替也有一个单独的 SELECT:
这也适用于多行。
The RETURN value actually comes back as an special OUTPUT parameter. SELECT gives a result set for ExecuteScalar.
You can use the OUTPUT clause instead of a separate SELECT too:
This will work for multiple rows too.
您需要添加另一个参数,其方向为
ReturnValue
:执行后该参数的值将作为返回值:
You need to add another parameter that has a direction of
ReturnValue
:The value of this parameter after execution will be the return value: