Advertisement
ramkumar_mst

Merge Statement in MSSQL

Apr 28th, 2022
2,265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 2.26 KB | None | 0 0
  1. Merge statement introduced in sql server 2008 allows us to perform insert, update & delete in one statement. We no longer have to use multiple statement for performing insert/update/delete.
  2.  
  3. With merge statement we requires 2 tables
  4.     i) Source table - contain changes that needs to be applied to the source table.
  5.     ii) Target table - table that requires changes (insert/update/delete)
  6.    
  7.     Merge statement joins the target table to source table by using common column in both the tables. Based on how the rows matchup. We can perform insert/update/delete on target table.
  8.    
  9.     Syntax:
  10.     Merge [target]  as t
  11.     Using [source] as s
  12.     On [join condition]
  13.     When matched then [updated statement]
  14.     When not matched by target then [ insert statement]
  15.     When not matched by source then [delete statement];
  16.    
  17.     Last statement should end with semi colon (;)
  18.    
  19.     E.g.:
  20.     Merge into studenttarget as t
  21.     Using studentsource as s
  22.     On t.id =s.id
  23.     When matched then update set t.name = s.name
  24.     When not matched by target then insert (id,name) values (s.id,s.name)
  25.     When not matched by source then delete;
  26.    
  27.     If delete is not required in above condition then we can omit the entire case.
  28.    
  29.     MERGE INTO dbo.PROJECTS_TESTS AS ps
  30. USING #temp_Test AS tC
  31.   ON ps.PROJECTID = tC.projectId   AND ps.ANOTHERTID = tC.anotherLink   AND ps.DOMAINID = tC.DOMAINID   AND ps.is_test = tC.test_project
  32. WHEN NOT MATCHED
  33. THEN INSERT ( PROJECTID, ANOTHERTID, DOMAINID, is_test)
  34. VALUES ( tC.PROJECTID, tC.ANOTHERTID, tC.DOMAINID, tC.test_project)
  35.    
  36.     Example : (Only update & insert rows that changed? Try using EXISTS and EXCEPT with merge)
  37.     MERGE INTO #Customer c
  38. USING #Updates u ON u.CustomerID = c.CustomerID
  39. WHEN MATCHED AND EXISTS (
  40.                     SELECT c.FirstName, c.MiddleName, c.LastName, c.DateOfBirth
  41.                     EXCEPT
  42.                     SELECT u.FirstName, u.MiddleName, u.LastName, u.DateOfBirth
  43.                 )
  44. THEN
  45.     UPDATE SET c.FirstName    = u.FirstName,
  46.                 c.MiddleName  = u.MiddleName,
  47.                 c.LastName    = u.LastName,
  48.                 c.DateOfBirth = u.DateOfBirth
  49. WHEN NOT MATCHED BY TARGET
  50. THEN
  51.     INSERT (CustomerID, FirstName, MiddleName, LastName, DateOfBirth)
  52.     VALUES (u.CustomerID, u.FirstName, u.MiddleName, u.LastName, u.DateOfBirth);
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement