试图获取 SELECT SCOPE_IDENTITY() 作为 c# 变量

Trying to get SELECT SCOPE_IDENTITY() as c# variable

我要在一个 table 中插入一行,然后想要获取新 ID,以便我可以将其添加到另一个变量中,我已经在其中存储了电子邮件地址。

 var db = Database.Open("myDB");
 var insertCommand1 = "INSERT INTO myDB (FirstName, LastName) Values(@0, @1)";                       
 db.Execute(insertCommand1, first, last);
 var lastInsertedId = db.QueryValue("SELECT SCOPE_IDENTITY()");

 var insertCommand2 = "INSERT INTO email (id_person, email) Values(@0, @1)";
 db.Execute(insertCommand2, lastInsertId, email);

其中 id_person 是我在第一个 table 中创建的 ID。当我 运行 代码时,我得到 lastInsertedId = {}。为什么它没有为我的第一个 table 获取主键 int 而不是 null 的 id_person 的值? --蒂姆

来自 the documentation of SCOPE_IDENTITY(),强调我的:

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

因为您使用了两个查询,所以它们被视为两个批次。您需要在单个查询中执行插入和 select。

我不知道你用的是什么库,所以我只是在猜测语法,但我相信你需要类似的东西

 var db = Database.Open("myDB");
 var insertCommand1 = "INSERT INTO myDB (FirstName, LastName) Values(@0, @1); " +
                      "SELECT SCOPE_IDENTITY()";
 var lastInsertedId = db.QueryValue(insertCommand1, first, last);

 var insertCommand2 = "INSERT INTO email (id_person, email) Values(@0, @1)";
 db.Execute(insertCommand2, lastInsertId, email);

如果数据库在 SQL SERVER ,创建一个 SQL 参数并将方向设置为 "Output"。 请检查此 link :

Getting the identity of the most recently added record

很容易从 SQL 服务器取回 SCOPE_IDENTITY() 值。我将举一个例子,我能够在 c# 标签中打印 SCOPE_IDENTITY() 数据。

  • 我的代码片段在从数据插入中提交
btnSubmit_Click()
{
    Random s = new Random();

    cmd = new SqlCommand("INSERT INTO [dbo].[tblMemberAccount] ([Userid], [User_pwd], [User_mobile], [User_referal], [UserWallet]) VALUES(@Userid, @User_pwd, @User_mobile, @User_referal, @UserWallet) ​select scope_identity()", cons); 

    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Userid",s.Next(4506,9999));
    cmd.Parameters.AddWithValue("@User_pwd",txtPassword.Text);
    cmd.Parameters.AddWithValue("@User_mobile",txtPhoneNumber.Text);
    cmd.Parameters.AddWithValue("@User_referal",txtReferral.Text);
    cmd.Parameters.AddWithValue("@UserWallet",10);
    cons.Open();
    int g = Convert.ToInt32(cmd.ExecuteScalar());
    cons.Close();
    lblConfirm.Text = "Member " +g+ " added successfully!";
}

此处值 'g' 返回 scope_identity 值。