Skip to content
Advertisement

SQL Server: update rows that take part in grouping

I’m using SQL Server 2017 (v14.0).

I have two tables with one-to-many relationship. I need to group the rows in the “Orders” table and by this info create the row in the “Transactions” table, then I need set the relationship – for a created transaction I need set the TransactionId to related order’s rows in one query/transaction flow to keep the consistency.

I correctly insert the new row by grouped data, but can’t update the related rows in “Orders” table to set the relationship (TransactionId) for related “Transactions”.

Can you, please, help with composing the query statement or get the clue to move in the right direction?

Advertisement

Answer

The problem with the OUTPUT clause in an INSERT statement is that it doesn’t allow you to select any field from the source table.

You can achieve this using MERGE statement instead:

Demo here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement