From the UI I pass a datatable to a stored procedure. The type of that parameter is a user defined table field with the following structure
Personkey int
ComponentKey varchar
This data needs to go into a table, and data that exists in the table but is not in the datatable should be deleted.
Example table data
PersonKey ComponentKey
123 A1
456 B9
And my datatable has 2 rows, one matching row and one new row
Example datatable data
PersonKey ComponentKey
123 A1
786 Z6
The result is that the 456/B9 row should be deleted, nothing should happen to the 123/A1 row, and the 786/Z6 row should be inserted.
I believe I can use the MERGE statement but I am not sure how to form it.
I understand that WHEN NOT MATCHED I should do the insert but where does the delete part come into it?
MERGE Components
USING @passedInData
ON PersonKey = DatatblPersonKey AND ComponentKey = DatatblComponentKey
WHEN MATCHED THEN
-- DO nothing...
WHEN NOT MATCHED
INSERT (PersonKey, ComponentKey) VALUES (DatatblPersonKey, DatatblComponentey);
Edit: Just to be clear, the datatable could contain many rows for the same person key, but the component key would be different.
Example datatable data
PersonKey ComponentKey
123 Z6
123 C5
Example table data
PersonKey ComponentKey
123 A1
456 B9
The result after inserting the above datatable should be
PersonKey ComponentKey
123 Z6
123 C5
456 B9
Notice that 123/A1 has been deleted and 456/B9 is still in the table.