Pages

Sunday, May 4, 2014

SQL Server XQuery Methods

Sql Server provides xquery methods to query xml file or xml data. Using these methods we can Insert, Update, Delete data in xml file or in XML Data Type variable. In Sql Server XQuery statements are case sensitive since xml is case sensitive. Hence while query to xml data remember this thing.

XQuery Methods

we have following xml data to implement all the XQuery methods given below.

  1. xml.exist()

    This method returns a boolean value depends upon the condition in this method like as
    1. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@ymail.com"]') as Result1
    2. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@yahoo.com"]') as Result2
  2. xml.query()

    This method takes an XQuery statement and returns an instance of the XML data type like as
    1. SELECT @xml.query('/Suppliers/User') as Users
    1. SELECT @xml.query('distinct-values( data(/Suppliers/User/Item/@No))') as Items
  3. xml.value()

    This method takes an XQuery statement and returns a single value after type casting like as
    1. SELECT @xml.value('/Suppliers[1]/User[1]/@Email', 'VARCHAR(20)') as ResultEmail1
    2. SELECT @xml.value('/Suppliers[1]/User[2]/@Email', 'VARCHAR(20)') as ResultEmail2
  4. xml.nodes()

    This method takes an XQuery statement and returns a single value after type casting like as
    1. SELECT x.value('@UserNo', 'int') AS UserNo, x.value('@Email', 'varchar(50)') AS Email
    2. FROM @xml.nodes('/Suppliers/User') TempXML (x)
    3. SELECT x.value('../@UserNo', 'int') AS UserNo, x.value('../@Email', 'varchar(50)') AS Email, x.value('@Name', 'varchar(50)') AS ItemName
    4. FROM @xml.nodes('/Suppliers/User/Item') TempXML (x)
  5. xml.modify()

    This method takes an XQuery statement and modify the xml data like as
    1. --Insert node in the end of XML
    2. SET @xml.modify ('insert as last into (/Suppliers)[1]')
    3. SELECT @xml;
    1. --Update node in xml
    2. DECLARE @UserNo int =120
    3. SET @xml.modify ('replace value of (/Suppliers/User/@UserNo)[1] with sql:variable("@UserNo")')
    4. SELECT @xml;
    1. --Update node in xml conditionally
    2. SET @xml.modify(' replace value of (/Suppliers/User/@UserNo)[1] with ( if (count(/Suppliers/User[1]/Item) > 2) then "3.0" else "1.0" ) ')
    3. SELECT @xml;
    1. --Delete node in xml SET @xml.modify(' delete Suppliers/User/Item[@No=1]')
    2. SELECT @xml;
    1. --Delete node in xml depends on condition
    2. DECLARE @ItemNo int=1
    3. SET @xml.modify(' delete Suppliers/User/Item[@No=sql:variable("@ItemNo")]')
    4. SELECT @xml;
Summary
In this article I try to explain the Sql Server XQuery methods with example. I hope after reading this article you will be able to query xml in Sql Server. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

No comments:

Post a Comment