DECLARE @PayRoll TABLE(EmpID INT, Salary INT, AddAmt INT) -- Declare table
INSERT INTO @PayRoll VALUES(1,2500,0),(2,100,0),(3,2700,0) --Insert sample records
MERGE @PayRoll AS PayRoll USING (SELECT EmpID,Salary FROM @PayRoll) AS PayRollAd -- Update the payroll table by taking values from that same table ON PayRoll.EmpID = PayRollAd.EmpID WHEN MATCHED AND PayRoll.Salary < 100 THEN DELETE -- If employee salary less than 100 then delete WHEN MATCHED THEN UPDATE SET PayRoll.AddAmt = (PayRoll.Salary / 10) -- If employee salary greater than 100 then update the additional amount WHEN NOT MATCHED THEN INSERT(EmpID, Salary) VALUES (PayRollAd.EmpID,2500); -- if employee is not there then insert (this scenario will come only when we use different table for merge)
SELECT * FROM @PayRoll
Semicolon is mandatory after the merge statement. This is very important and it is an often forgotten fact!
When there is a MATCH clause used along with some condition, it has to be specified first among all other WHEN MATCH clauses.
Balaji M Kundalam edited Revision 8. Comment: Typography - minor correction
Naomi N edited Revision 6. Comment: Minor edit
Maheshkumar S Tiwari edited Revision 5. Comment: Added Tag and formatting
Maheshkumar S Tiwari edited Revision 4. Comment: Added TOC and formatting
Naomi N edited Revision 2. Comment: Added link to Alexander Kuznetsov article
Naomi N edited Revision 1. Comment: Minor edit
BTW, a bit funny example - why would we delete underpaid employees from the Payroll?
Nice and simple article - good for beginners