简体   繁体   中英

How do you insert into two tables simultaneously?

    StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO Threads(");//How can i modify that statement
sb.Append(" SELECT @Repuation, @WiningComment");
sb.Append(" FROM Users AS u");
sb.Append(" INNER JOIN Threads AS t ON t.UsersID=u.UsersID");
sb.Append(" WHERE t.ThreadsID=@ThreadID");

I have users table and threads table. I want to insert the @Reputation into the users table and @winingComment into the threads table?! How do i achieve that?

I would suggest you to do 2 separate INSERT in a TRANSACTION

BEGIN TRANSACTION
INSERT [...]
INSERT [...]
COMMIT TRANSACTION

Technically, the transaction guaranties the atomicity of your requests.

You will need to do 2 seperate INSERT statements as you can't insert data into 2 tables simultaneously.

I think you would just do two separate INSERT statements. If you want to make sure that this is an atomic operation (either both or neither get inserted) then you can wrap them in a transaction. When the transaction is commited, the inserts are done simultaneously.

Hope that helps,

John

You can't. They are going to have to be two statements no matter how you look at it. You could use a trigger to emulate the feel of doing a single INSERT , but that's got pretty bad code smell IMO.

If you just want to send the statements on a single command, terminate the first with a semi-colon and send it as one batch to a SqlCommand .

new SqlCommand("INSERT INTO Table1 (ID) SELECT 1; INSERT INTO Table2 (SomeField) SELECT 'Some value.';", some_db_connection).ExecuteNonQuery();

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