开发者

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 ta开发者_运维百科ble!! 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();


Using Merge statement of Sql 2008 may help in performing operations in multiple table.

Please check once

http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/

http://technet.microsoft.com/en-us/library/bb510625.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜