There are some cases when you need to update an existing record in a table from another table or insert a new record if one doesn't exist. Here is a quick way to do either procedure.
/*
TABLE_MAIN
code_id period empl_id amount
----------------- ----------- ---------
105 200108 100 500
100 200108 100 300
100 200109 100 250
105 200109 100 350
100 200110 200 0
150 200110 200 0
TABLE_NEW
code_id period amount
------ ----------- ----------
100 200110 500
105 200110 900
150 200110 200
100 200111 375
105 200111 750
150 200111 900
--update existing in TABLE_MAIN records with new amount
from the TABLE_NEW
*/
UPDATE TABLE_MAIN
SET amount= n.amount
FROM TABLE_MAIN t LEFT OUTER JOIN TABLE_NEW n
ON t.code_id = n.code_id AND t.period = n.period
WHERE n.code_id IS NOT NULL
-- 'Insert new records into TABLE_MAIN
INSERT INTO TABLE_MAIN(code_id, period, amount)
SELECT n.code_id , n.period, n.amount
FROM TABLE_NEW n LEFT OUTER JOIN TABLE_MAIN t
ON t.code_id = n.code_id AND t.period = n.period
WHERE t.code_id IS NULL
go
/*
Final results:
code_id period empl_id amount ------------ ----------- --------- 105 200108 100 500 100
Requires Free Membership to View
200108 100 300 100 200109 100 250 105 200109 100 350 100 200110 200 500 150 200110 200 200 100 200111 NULL 375 105 200110 NULL 900 105 200111 NULL 750 150 200111 NULL 900 */
For More Information
- What do you think about this tip? E-mail the Editor at tdichiara@techtarget.com with your feedback.
- The Best SQL Server Web Links: tips, tutorials, scripts, and more.
- Have an SQL Server tip to offer your fellow DBA's and developers? The best tips submitted will receive a cool prize--submit your tip today!
- Ask your technical SQL Server questions--or help out your peers by answering them--in our live discussion forums.
- Check out our Ask the Experts feature: Our SQL, Database Design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
This was first published in January 2002

Join the conversationComment
Share
Comments
Results
Contribute to the conversation