Sunday, September 07, 2008

SQL Server 2008: MERGE Statement

Previous version of SQL Server required INSERT, UPDATE or DELETE statement in order to perform MERGE function from two table with similar attributes. Now with the release of SQL Server 2008 along together with the support of MERGE statement which perform the long tedious statement within few lines of statement. To keep things short and simple, just review the sample statement and sample tables below:

sqltable_new


sqltable_existing


sqlstatement


Base on the image, the MERGE statement will perform merging function as dbo.New_Table will merge with dbo.Existing_Table with the condition of MATCHED and NOT MATCHED. Basically the MERGE statement will check each row with ID is the matching criteria and if it match then UPDATE SET will update dbo.Existing_Table selected column with dbo.New_Table selected column. If the ID not match then INSERT will insert dbo.New_Table row into dbo.Existing_Table. The result is show below on dbo.Existing_Table:

sqltable_result

This is really a basic MERGE statement as more complex MERGE can be done which allow flexible condition and result to be shown. I will blog more on SQL Server 2008 MERGE Statement once I have futher knowledge on this function.

No comments: