简体   繁体   English

使用范围标识时遇到一些麻烦

[英]Having some trouble using scope identity

I have two tables, one containing names, and one containing rates and other data that is lined to each name. 我有两个表,一个包含名称,另一个包含与每个名称对应的费率和其他数据。 After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates. 在我向表A中插入一个新名称后,我想让新生成的PK现在用来插入我的其他表B中的费率。

How can I do this? 我怎样才能做到这一点? I read about scope_identity online but I'm not sure how to use it. 我在线阅读了scope_identity但我不确定如何使用它。

This is what I have so far: 这是我到目前为止:

SqlConnection con = new SqlConnection(pubvar.x);

SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";

SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";

SELECT SCOPE_IDENTITY();

con.Open();
command.ExecuteNonQuery();
con.Close();

Considering the case you've described, I don't see any need to return the identity from the database. 考虑到您所描述的情况,我认为没有必要从数据库返回身份。 You can simply issue both statements in one command: 您只需在一个命令中发出两个语句:

using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
    Connection = cnx,
    CommandText = @"
    insert into A (Name) values (@name)
    insert into B (A_ID, Rate) values (scope_identity(), @rate)
    ",
    Parameters =
    {
        new SqlParameter("@name", name),
        new SqlParameter("@rate", .5m) //sample rate
    }
})
{
    cnx.Open();
    cmd.ExecuteNonQuery();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM