Domanda

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.

How can I do this? I read about scope_identity online but I'm not sure how to use it.

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();
È stato utile?

Soluzione

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();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top