Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert and update records in one TSQL statement?

Tags:

tsql

I have a table BigTable and a table LittleTable. I want to move a copy of some records from BigTable into LittleTable and then (for these records) set BigTable.ExportedFlag to T (indicating that a copy of the record has been moved to little table).

Is there any way to do this in one statement?

I know I can do a transaction to:

  1. moves the records from big table based on a where clause
  2. updates big table setting exported to T based on this same where clause.

I've also looked into a MERGE statement, which does not seem quite right, because I don't want to change values in little table, just move records to little table.

I've looked into an OUTPUT clause after the update statement but can't find a useful example. I don't understand why Pinal Dave is using Inserted.ID, Inserted.TEXTVal, Deleted.ID, Deleted.TEXTVal instead of Updated.TextVal. Is the update considered an insertion or deletion?

I found this post TSQL: UPDATE with INSERT INTO SELECT FROM saying "AFAIK, you cannot update two different tables with a single sql statement."

Is there a clean single statement to do this? I am looking for a correct, maintainable SQL statement. Do I have to wrap two statements in a single transaction?

like image 615
bernie2436 Avatar asked Sep 13 '12 13:09

bernie2436


1 Answers

You can use the OUTPUT clause as long as LittleTable meets the requirements to be the target of an OUTPUT ... INTO

UPDATE BigTable
SET ExportedFlag = 'T'
OUTPUT inserted.Col1, inserted.Col2 INTO LittleTable(Col1,Col2)
WHERE <some_criteria>

It makes no difference if you use INSERTED or DELETED. The only column it will be different for is the one you are updating (deleted.ExportedFlag has the before value and inserted.ExportedFlag will be T)

like image 61
Martin Smith Avatar answered Sep 30 '22 13:09

Martin Smith