I have written a working T-SQL MERGE statement. The premise is that Database A contains records about customer’s support calls. If they are returning a product for repair, Database B is to be populated with certain data elements from Database A (e.g. customer name, address, product ID, serial number, etc.) So I will run an SQL Server job that executes an SSIS package every half hour or so, in which the MERGE will do one of the following:
- If the support call in Database A requires a product return and it
is not in Database B, INSERT it into Database B..- If the support call in Database A requires a product return and it
is in Database B – but data has changed – UPDATE it in Database B.- If there is a product return in Database B but it is no longer
indicated as a product return in Database A (yes, this can happen – a customer can change their mind at a later time/date and not want to pay for a replacement product), DELETE it from Database
B.
My problem is that Database B has an additional table with a 1-to-many FK relationship with the table being populated in the MERGE. I do not know how, or even if, I can go about using a MERGE statement to first delete the records in the table with FK constraint before deleting the records as I am currently doing in my MERGE statement.
Obviously, one way would be to get rid of the DELETE in the MERGE and hack out writing IDs to delete in a temp table, then deleting from the FK table, then the PK table. But if I can somehow delete from both tables in WHEN NOT MATCHED BY SOURCE that would be cleaner code. Can this be done?
You can only
UPDATE,DELETE, orINSERTinto/from one table per query.However, if you added an
ON DELETE CASCADEto theFKrelationship, the sub-table would be cleaned up as you delete from the primary table, and it would be handled in a single operation.