In the previous article we saw the Merge Statement.

These articles will work around the merge statement over XML data type. We know that the XML data type SQL SERVER. The XML Data type stores XML data using Bulk Insert of the 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
  3. Merge Statement usign Xml Data.
  4. Merge into Student as Trg
  5. Using (select d.x.value('Name[1]','varchar(20)') as Name ,
  6. d.x.value('Marks[1]','int') as Marks from
  7. @data.nodes('/Root/Student')as d(x)) as Src
  8. on Trg.Name=Src.Name
  9. When Matched Then update set
  10. Trg.Marks=Src.Marks
  11. when not matched by target then
  12. insert (Name,Marks) values(Src.Name,Src.Marks);
  13. select * from Student
Here all the rows are 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>'
  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


Remove some data from 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