gpt4 book ai didi

C# Scope_Identity 问题

转载 作者:行者123 更新时间:2023-11-30 14:34:14 25 4
gpt4 key购买 nike

浏览了一些答案,但似乎对我不起作用。

我需要返回一个表的 ID 字段,这样我就可以在程序的不同部分使用它,我试过使用

    Convert.ToInt32(sqlComm.ExecuteScalar());

但没有运气,同样的

    Convert.ToInt32(sqlComm.Parameters["ID"].Value);

并且两者都返回 0,即使记录确实插入到表中也是如此。

我将转储下面的代码,任何人都可以看到我做错了什么吗?

    using (SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand sqlComm = new SqlCommand("up_Insert_Address", sqlConnect))
{
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add("@AddressID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
sqlComm.Parameters.Add("@AddressLineOne", SqlDbType.NVarChar, 40).Value = address.AddressLineOne;

try
{
sqlComm.Connection.Open();
return Convert.ToInt32(sqlComm.ExecuteScalar());
}

catch (SqlException)
{
}

finally
{
sqlComm.Connection.Close();
}
}
}

和存储过程:

    @AddressID   Bigint OUTPUT,
@AddressLineOne NVarChar(40)
AS
BEGIN
BEGIN TRY
INSERT INTO Address
(
AddressLineOne
)
VALUES
(
@AddressLineOne
)

SET @AddressID = SCOPE_IDENTITY();
END TRY
BEGIN CATCH
DECLARE @Err nvarchar(500)
SET @Err = ERROR_MESSAGE()
RAISERROR(@Err, 16, 1)
END CATCH
END

最佳答案

你应该使用

Convert.ToInt64(sqlComm.Parameters["@AddressID"].Value);

在使用 ExceuteNonQuery 执行命令后。为了将来引用,ExecuteScalar 返回查询返回的结果集中第一行的第一列。您没有返回任何内容,只是设置了 OUTPUT 参数的值。

此外,您绝对不应吞下任何 SqlException。由于您的命令和连接已经在 using block 中,因此您不需要添加另一个 try/catch/finally。将其更改为:

//try
//{
sqlComm.Connection.Open();
sqlComm.ExecuteNonQuery();
return Convert.ToInt64(sqlComm.Parameters["@AddressID"].Value);
// using Int64 since the SQL type is BigInt
//}

//catch (SqlException)
//{
//}

//finally
//{
// sqlComm.Connection.Close();
//}

关于C# Scope_Identity 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14383997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com