1

How can I insert values into two tables at once? if it not successful, both table should rollback.

I am using SQL server and the query passe throw C# code.

Haroon A.
  • 371
  • 2
  • 7
  • 19
  • 1
    Why can't you use two insert statements? Unless you use an `OUTPUT` clause or a trigger, an `INSERT` statement can only affect a single table. – Aaron Bertrand Feb 14 '12 at 19:40

3 Answers3

4

You could either run the two queries as one statement

insert into table1 (...) values (...); insert into table2 (...) values (...)

or write a trigger to do the second INSERT.

D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • Yes, this is true: insert into table1 (...) values (...); insert into table2 (...) values (...) but it should be in one transaction. because if the first insertion failed the second should not executed – Haroon A. Feb 15 '12 at 10:31
4

I would typically write a stored procedure to take in all of the values you want to write out, then call a series of INSERT INTO statements wrapped in a transaction.

If you provide more information, such as table structure and sample data, we can help you further.

Nick Heidke
  • 2,787
  • 2
  • 34
  • 58