Showing posts from October, 2017

T-SQL Basics: MERGE Statement

One useful sentence when you need to add data to an existing table from an external source or database, and you are not sure if some of the data exists or not, is the MERGE statement. This statement can significantly reduce the code needed to perform validations and insert data from source to destination, or updating it if already exists, even you can choose to delete data instead.   The general form is: MERGE INTO <target_table> USING <table_source> ON <merge_search_condition> [ WHEN MATCHED [ AND <clause_search_condition> ] THEN <merge_matched> ] [ ...n ] [ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ] THEN <merge_not_matched> ] [ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ] THEN <merge_matched> ] [ ...n ]; Let us watch an example of use, using the AdventureWorks database, I have created a test table with fewe