0

我有两张表,一张包含姓名,一张包含费率和与每个姓名对应的其他数据。在表 A 中插入一个新名称后,我想获取新自动生成的 PK,以便现在用于插入到我的另一个表 B 中。

我怎样才能做到这一点?我在网上阅读过,scope_identity但我不知道如何使用它。

这是我到目前为止所拥有的:

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();
4

1 回答 1

2

考虑到您描述的情况,我认为没有必要从数据库返回身份。您可以简单地在一个命令中发出两个语句:

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();
}
于 2013-11-22T19:21:30.920 回答