In the last article we saw about the Merge Statement.

These articles will work around the merge statement over the XML data type. We know about the XML data type of SQL Server. The XML Data type stores XML data using Bulk Insert Data into SQL Tables.

Example
  1. --Create Student Table
  2. if object_id('Student') is null
  3. create table Student(id int identity(1,1) ,Name varchar(20), Marks int)

  1. Declare Xml Data Type and Assign Some Xml Data.
  2. Declare @Data xml
  3. set @Data=
  4. '<Root>
  5. <Student>
  6. <Name>Rakesh</Name>
  7. <Marks>80</Marks>
  8. </Student>
  9. <Student>
  10. <Name>Mahesh</Name>
  11. <Marks>90</Marks>
  12. </Student>
  13. <Student>
  14. <Name>Gowtham</Name>
  15. <Marks>60</Marks>
  16. </Student>
  17. </Root>'
  18. select @Data as StudentData

  1. select * from Student
  2. --no record in Student Table
Merge Statement usign XML Data
  1. Merge into Student as Trg
  2. Using (select d.x.value('Name[1]','varchar(20)') as Name ,
  3. d.x.value('Marks[1]','int') as Marks from
  4. @data.nodes('/Root/Student')as d(x)) as Src
  5. on Trg.Name=Src.Name
  6. When Matched Then update set
  7. Trg.Marks=Src.Marks
  8. when not matched by target then
  9. insert (Name,Marks) values(Src.Name,Src.Marks);
  10. select * from Student
Here all the rows have been inserted because no matching records existed in the Student table with the Name Key.



This time I changed the XML Data Marks column with the same data. This time we need to update the Student table data.
  1. Declare @Data xml
  2. set @Data=
  3. '<Root>
  4. <Student>
  5. <Name>Rakesh</Name>
  6. <Marks>60</Marks>
  7. </Student>
  8. <Student>
  9. <Name>Mahesh</Name>
  10. <Marks>90</Marks>
  11. </Student>
  12. <Student>
  13. <Name>Gowtham</Name>
  14. <Marks>80</Marks>
  15. </Student>
  16. </Root>'
  17. Merge into Student as Trg
  18. Using (select d.x.value('Name[1]','varchar(20)') as Name
  19. ,d.x.value('Marks[1]','int') as Marks from
  20. @data.nodes('/Root/Student')as d(x)) as Src
  21. on Trg.Name=Src.Name
  22. When Matched Then update set
  23. Trg.Marks=Src.Marks
  24. when not matched by target then
  25. insert (Name,Marks) values(Src.Name,Src.Marks);
  26. select * from Student


The following will remove some data from the XML (“Here GoWtham“ record):
  1. Declare @Data xml
  2. set @Data=
  3. '<Root>
  4. <Student>
  5. <Name>Rakesh</Name>
  6. <Marks>60</Marks>
  7. </Student>
  8. <Student>
  9. <Name>Mahesh</Name>
  10. <Marks>90</Marks>
  11. </Student>
  12. </Root>'
  13. Merge into Student as Trg
  14. Using (select d.x.value('Name[1]','varchar(20)') as Name
  15. ,d.x.value('Marks[1]','int') as Marks from
  16. @data.nodes('/Root/Student')as d(x)) as Src
  17. on Trg.Name=Src.Name
  18. When Matched Then update set
  19. Trg.Marks=Src.Marks
  20. when not matched by target then
  21. insert (Name,Marks) values(Src.Name,Src.Marks)
  22. when not matched by source then Delete;
  23. select * from Student