简体   繁体   中英

Insert into multiple tables using INSERT_IDENTITY - ADO.Net

I want to INSERT records in multiple tables with ADO.NET.

I want to INSERT a new record into a table called Professionals. It has a foreign key mapped to a different table. tables:

桌子

Example:

 cmd.CommandText = "insert T_Name select (Name.T_Name,Date.T_Name,DId.Date) values (@N,GETDATE(),???)from T_Name inner join Date ON Date.DId=T_Name.DId; ";
 cmd.Parameters.AddWithValue("@N", txt_Name.Text);

OR

...

How can I add values into these tables at one time?

After add insert sql for first table

SELECT SCOPE_IDENTITY();

then you get last inserted id. You can use second sql parameters.

Example:

        var dateNow = DateTime.Now;
        var cmd = new SqlCommand("INSERT INTO Date (Date) VALUES (@Date);SELECT SCOPE_IDENTITY();", cnn);
        cmd.Parameters.AddWithValue("@Date", dateNow);
        var insertedId = cmd.ExecuteScalar();
        cmd = new SqlCommand("INSERT INTO T_Name (Name,Date,DId) VALUES (@Name,@Date,@DId);", cnn);
        cmd.Parameters.AddWithValue("@Name", "Test");
        cmd.Parameters.AddWithValue("@Date", dateNow);
        cmd.Parameters.AddWithValue("@DId", insertedId);
        cmd.ExecuteNonQuery(); //or ExecuteScalar() for get last insertedId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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