You are on page 1of 11

XML Basics XML Can be used for several actions related to database.

The major uses are retrieving relational data as xml, Passing data as XML to the database and Sorting and Querying an actual XML document or fragment in the database. XML Syntax XML data type For XML Clause Xpath Xquery functions XML Syntax Properties of XML 1. Have a root element 2. Matching tags (opening and closing tags). 3. Case sensitive 4. Extensible Example of XML The person is the root of the XML element which contain "fname", "lname" and "address" as child nodes. "address" node contain "street", "city" and "state" as child node. <person> <fname>Subodh</fname> <lname>Kant</lname> <address> <street>Rasulgarh</street> <city>BBSR</city> <state>Odisha</state> </address> </person> XML data type XML Data type let you store XML documents and XML fragments in a SQL server database. An XML Fragment is an XML instance that is missing a single top level element. With XML as a data type you can create and store xml as a variable and in columns respectively. XML data type can be typed or untyped. Typed simply means that an XML schema collection is assigned to the type to verify its content.
Create a table with XML as a column CREATE TABLE PEOPLE ( ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY, PERSON XML NOT NULL ) Insert a row as XML document: INSERT INTO PEOPLE(PERSON) VALUES(

'<person> <fname>Subodh</fname> <lname>Kant</lname> <address> <street>Rasulgarh</street> <city>BBSR</city> <state>Odisha</state> </address> </person>') Insert another row as XML fragment: INSERT INTO PEOPLE(PERSON) VALUES( '<person>XYZ</person> <person>ABC</person> <person>PQR</person>')

FOR XML Clause: FOR XML clause is used to retrieve tabular data as XML. In SQL server 2008 there are four flavors of FOR XML (Mode) RAW AUTO EXPLICIT PATH To understand these first create a table which contains two tables and some data inside it. Company table contains company information and employee table contain employee information along with the company id in which the employee is working.
CREATE TABLE COMPANY ( COMPANY_ID INT IDENTITY PRIMARY KEY, COMPANY_NAME VARCHAR(50), COMPANY_ADDRESS VARCHAR(200) ) CREATE TABLE EMPLOYEE ( EMP_ID INT IDENTITY PRIMARY KEY, EMP_LNAME VARCHAR(20), EMP_FNAME VARCHAR(20), EMP_EMAIL VARCHAR(50), COMPANY_ID INT FOREIGN KEY REFERENCES COMPANY(COMPANY_ID) ) INSERT INTO COMPANY(COMPANY_NAME,COMPANY_ADDRESS) VALUES('ABC Corporation','XYZ Street, BBSR, Odisha') INSERT INTO COMPANY(COMPANY_NAME,COMPANY_ADDRESS) VALUES('DEF Corporation','PQR Street, Ranchi, Jharkhand') INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID)

VALUES('Subodh','Kant','subodh@test.test',1) INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID) VALUES('Manas','Panda',NULL,1) INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID) VALUES('Ashish','Tondon','ashish@test.test',1) INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID) VALUES('Niraj','Choubey','Niraj@test.test',2) INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID) VALUES('Abhijit','Kalita','abhijit@test.test',2) INSERT INTO EMPLOYEE(EMP_FNAME,EMP_LNAME,EMP_EMAIL,COMPANY_ID) VALUES('Manoranjan','Mohapatra',NULL,2)

FOR XML RAW:It is the simplest implementation of FOR XML clause. FOR XML Query return basically return each row as an XML element and each column as an XML attribute.
SELECT COMPANY_ID, COMPANY_NAME, COMPANY_ADDRESS FROM COMPANY FOR XML RAW output <row COMPANY_ID="1" COMPANY_NAME="ABC Corporation" COMPANY_ADDRESS="XYZ Street, BBSR, Odisha"/> <row COMPANY_ID="2" COMPANY_NAME="DEF Corporation" COMPANY_ADDRESS="PQR Street, Ranchi, Jharkhand" />

Adding a root and name to an XML element


SELECT COMPANY_ID, COMPANY_NAME, COMPANY_ADDRESS FROM COMPANY FOR XML RAW('COMPANY'),ROOT('COMPANIES') output <COMPANIES> <COMPANY COMPANY_ID="1" COMPANY_NAME="ABC Corporation" COMPANY_ADDRESS="XYZ Street, BBSR, Odisha" /> <COMPANY COMPANY_ID="2" COMPANY_NAME="DEF Corporation" COMPANY_ADDRESS="PQR Street, Ranchi, Jharkhand" /> </COMPANIES>

If null values come in the columns it will omit the attribute in XML, like for some employee email is null so email attribute in not there for those employees
SELEC EMP_ID, EMP_FNAME + ' ' + EMP_LNAME AS NAME, EMP_EMAIL, COMPANY_ID

FROM EMPLOYEE FOR XML RAW('EMPLOYEE'),ROOT('EMPLOYEE') output <EMPLOYEE> <EMPLOYEE <EMPLOYEE <EMPLOYEE <EMPLOYEE <EMPLOYEE <EMPLOYEE </EMPLOYEE>

EMP_ID="1" EMP_ID="2" EMP_ID="3" EMP_ID="4" EMP_ID="5" EMP_ID="6"

NAME="Subodh Kant" EMP_EMAIL="subodh@test.test" COMPANY_ID="1" /> NAME="Manas Panda" COMPANY_ID="1" /> NAME="Ashish Tondon" EMP_EMAIL="ashish@test.test" COMPANY_ID="1" /> NAME="Niraj Choubey" EMP_EMAIL="Niraj@test.test" COMPANY_ID="2" /> NAME="Abhijit Kalita" EMP_EMAIL="abhijit@test.test" COMPANY_ID="2" /> NAME="Manoranjan Mohapatra" COMPANY_ID="2" />

Instead of attributing if we want all the columns as an element we have to write a query like this
SELECT EMP_ID, EMP_FNAME + ' ' + EMP_LNAME AS NAME, EMP_EMAIL, COMPANY_ID FROM EMPLOYEE FOR XML RAW('EMPLOYEE'),ROOT('EMPLOYEES'), ELEMENTS output <EMPLOYEES> <EMPLOYEE> <EMP_ID>1</EMP_ID> <NAME>Subodh Kant</NAME> <EMP_EMAIL>subodh@test.test</EMP_EMAIL> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>2</EMP_ID> <NAME>Manas Panda</NAME> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>3</EMP_ID> <NAME>Ashish Tondon</NAME> <EMP_EMAIL>ashish@test.test</EMP_EMAIL> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>4</EMP_ID> <NAME>Niraj Choubey</NAME> <EMP_EMAIL>Niraj@test.test</EMP_EMAIL> <COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>5</EMP_ID> <NAME>Abhijit Kalita</NAME> <EMP_EMAIL>abhijit@test.test</EMP_EMAIL>

<COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>6</EMP_ID> <NAME>Manoranjan Mohapatra</NAME> <COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> </EMPLOYEES> If we want to show nodes for Null columns then we have to write the Query like this SELEC EMP_ID, EMP_FNAME + ' ' + EMP_LNAME AS NAME, EMP_EMAIL, COMPANY_ID FROM EMPLOYEE FOR XML RAW('EMPLOYEE'),ROOT('EMPLOYEES'), ELEMENTS XSINIL output <EMPLOYEES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <EMPLOYEE> <EMP_ID>1</EMP_ID> <NAME>Subodh Kant</NAME> <EMP_EMAIL>subodh@test.test</EMP_EMAIL> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>2</EMP_ID> <NAME>Manas Panda</NAME> <EMP_EMAIL xsi:nil="true" /> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>3</EMP_ID> <NAME>Ashish Tondon</NAME> <EMP_EMAIL>ashish@test.test</EMP_EMAIL> <COMPANY_ID>1</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>4</EMP_ID> <NAME>Niraj Choubey</NAME> <EMP_EMAIL>Niraj@test.test</EMP_EMAIL> <COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>5</EMP_ID> <NAME>Abhijit Kalita</NAME> <EMP_EMAIL>abhijit@test.test</EMP_EMAIL> <COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> <EMPLOYEE> <EMP_ID>6</EMP_ID>

<NAME>Manoranjan Mohapatra</NAME> <EMP_EMAIL xsi:nil="true" /> <COMPANY_ID>2</COMPANY_ID> </EMPLOYEE> </EMPLOYEES>

FOR XML AUTO:The AUTO mode differs from RAW in that it natively supports hierarchies. Hierarchies need to be simple because AUTO doesn't support more than one path of branches. ELEMENTS and XSINIL directive exist for AUTO and RAW but not for EXPLICIT and PATH. Example: A B C Works fine but this hierarchy will not work. A B C D
SELECT COMPANY.COMPANY_NAME, COMPANY.COMPANY_ID , EMPLOYEES.X, EMPLOYEE.EMP_FNAME , EMPLOYEE.EMP_LNAME, EMPLOYEE.EMP_ID FROM COMPANY COMPANY INNER JOIN EMPLOYEE EMPLOYEE ON EMPLOYEE.COMPANY_ID = COMPANY.COMPANY_ID CROSS JOIN (SELECT NULL AS X) AS EMPLOYEES ORDER BY COMPANY.COMPANY_ID FOR XML AUTO, ROOT('COMP_EMP') output <COMP_EMP> <COMPANY COMPANY_NAME="ABC Corporation" COMPANY_ID="1"> <EMPLOYEES> <EMPLOYEE EMP_FNAME="Subodh" EMP_LNAME="Kant" EMP_ID="1" /> <EMPLOYEE EMP_FNAME="Manas" EMP_LNAME="Panda" EMP_ID="2" /> <EMPLOYEE EMP_FNAME="Ashish" EMP_LNAME="Tondon" EMP_ID="3" /> </EMPLOYEES> </COMPANY> <COMPANY COMPANY_NAME="DEF Corporation" COMPANY_ID="2"> <EMPLOYEES> <EMPLOYEE EMP_FNAME="Niraj" EMP_LNAME="Choubey" EMP_ID="4" /> <EMPLOYEE EMP_FNAME="Abhijit" EMP_LNAME="Kalita" EMP_ID="5" /> <EMPLOYEE EMP_FNAME="Manoranjan" EMP_LNAME="Mohapatra" EMP_ID="6" /> </EMPLOYEES> </COMPANY> </COMP_EMP> FOR XML EXPLICIT: With this mode we can create any XML structure which is not supported by the

PATH mode. In this mode we must return a specific result set that is we must name our column in a specific way. EXPLICIT mode result set contains two columns Tag and parent.
SELECT 1 AS TAG, NULL AS PARENT, NULL AS "Companies!1!!element", NULL AS "Company!2!name", NULL AS "Company!2!id", NULL AS "Employee!3!name", NULL AS "Employee!3!id" UNION ALL SELECT 2 AS TAG, 1 AS PARENT, NULL AS "Companies!1!!element", COMPANY.COMPANY_NAME AS "Company!2!name", COMPANY.COMPANY_ID AS "Company!2!id", NULL AS "Employee!3!name", NULL AS "Employee!3!id" FROM COMPANY AS COMPANY UNION ALL SELECT 3 AS TAG, 2 AS PARENT, NULL AS "Companies!1!!element", NULL AS "Company!2!name", EMP.COMPANY_ID AS "Company!2!id", EMP.EMP_FNAME + ' ' + EMP.EMP_LNAME AS "Employee!3!name", EMP.EMP_ID AS "Employee!3!id" FROM EMPLOYEE AS EMP ORDER BY "Company!2!id",TAG FOR XML EXPLICIT output <Companies> <Company name="ABC Corporation" id="1"> <Employee name="Subodh Kant" id="1" /> <Employee name="Manas Panda" id="2" /> <Employee name="Ashish Tondon" id="3" /> </Company> <Company name="DEF Corporation" id="2"> <Employee name="Niraj Choubey" id="4" /> <Employee name="Abhijit Kalita" id="5" /> <Employee name="Manoranjan Mohapatra" id="6" /> </Company> </Companies>

FOR XML PATH: It is the best choice of different FOR XML modes for most solutions. PATH mode allows for the easy creation of different XML structures by simply intepreting column names specified using an Xpath-like expression when generating the XML result. This mode is very powerfull and easy to implement.

@xxx is used for attribute. text() is used for xml element text. node() is used to create a new XML node. comment() is used to add XML comment. 'XYZ node/@xyz' is used to add an attribute in XYZ XML element.
SELECT EMPLOYEE.EMP_ID AS "@id", EMPLOYEE.EMP_FNAME + ' ' + EMPLOYEE.EMP_LNAME AS "text()", EMPLOYEE.COMPANY_ID AS "AdditionalInfo/@CompanyId", EMPLOYEE.EMP_EMAIL AS "AdditionalInfo/text()", CAST('<test/>' AS XML) AS "node()", EMPLOYEE.COMPANY_ID AS "comment()" FROM EMPLOYEE FOR XML PATH('EMPLOYEE'), ROOT('EMPLOYEES') output <EMPLOYEES> <EMPLOYEE id="1">Subodh Kant<AdditionalInfo CompanyId="1">subodh@test.test</AdditionalInfo><test /><!--1--></EMPLOYEE> <EMPLOYEE id="2">Manas Panda<AdditionalInfo CompanyId="1" /><test /><!--1--></EMPLOYEE> <EMPLOYEE id="3">Ashish Tondon<AdditionalInfo CompanyId="1">ashish@test.test</AdditionalInfo><test /><!--1--></EMPLOYEE> <EMPLOYEE id="4">Niraj Choubey<AdditionalInfo CompanyId="2">Niraj@test.test</AdditionalInfo><test /><!--2--></EMPLOYEE> <EMPLOYEE id="5">Abhijit Kalita<AdditionalInfo CompanyId="2">abhijit@test.test</AdditionalInfo><test /><!--2--></EMPLOYEE> <EMPLOYEE id="6">Manoranjan Mohapatra<AdditionalInfo CompanyId="2" /><test /><!--2-></EMPLOYEE> </EMPLOYEES>

XPATH XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps. For more information about XPATH read this link W3-Schools and msdn. XQUERY When we store data in XML format we have to both Query and modify it. This is performed using a few methods provided by the XML data type. Lets create a XML temporary variable and then perform the xQuery methods on it.
DECLARE @TESTXML XML = N'<COMPANIES> <COMPANY> <COMPANY_NAME>ABC Corporation</COMPANY_NAME> <COMPANY_ID>1</COMPANY_ID> <EMPLOYEE> <EMP_FNAME>Subodh</EMP_FNAME> <EMP_LNAME>Kant</EMP_LNAME> <EMP_ID>1</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Manas</EMP_FNAME> <EMP_LNAME>Panda</EMP_LNAME>

<EMP_ID>2</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Ashish</EMP_FNAME> <EMP_LNAME>Tondon</EMP_LNAME> <EMP_ID>3</EMP_ID> </EMPLOYEE> </COMPANY> <COMPANY> <COMPANY_NAME>DEF Corporation</COMPANY_NAME> <COMPANY_ID>2</COMPANY_ID> <EMPLOYEE> <EMP_FNAME>Niraj</EMP_FNAME> <EMP_LNAME>Choubey</EMP_LNAME> <EMP_ID>4</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Abhijit</EMP_FNAME> <EMP_LNAME>Kalita</EMP_LNAME> <EMP_ID>5</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Manoranjan</EMP_FNAME> <EMP_LNAME>Mohapatra</EMP_LNAME> <EMP_ID>6</EMP_ID> </EMPLOYEE> </COMPANY> </COMPANIES>'

Query method: It is used to perform XQUERY against the XML instance to retrieve an XML fragment rather than tabular result or scalar value.
SELECT @TESTXML.query('COMPANIES/COMPANY[1]/EMPLOYEE') Output <EMPLOYEE> <EMP_FNAME>Subodh</EMP_FNAME> <EMP_LNAME>Kant</EMP_LNAME> <EMP_ID>1</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Manas</EMP_FNAME> <EMP_LNAME>Panda</EMP_LNAME> <EMP_ID>2</EMP_ID> </EMPLOYEE> <EMPLOYEE> <EMP_FNAME>Ashish</EMP_FNAME> <EMP_LNAME>Tondon</EMP_LNAME> <EMP_ID>3</EMP_ID> </EMPLOYEE>

SELECT @TESTXML.query(N' <TestNode> { for $o in /COMPANIES/COMPANY return <TESTCOMPANY Name="{data($o/COMPANY_NAME)}" Id="{data($o/COMPANY_ID)}"> <Employee Name="{data($o/EMPLOYEE/EMP_FNAME)}"/> </TESTCOMPANY> } </TestNode> ') Output <TestNode> <TESTCOMPANY Name="ABC Corporation" Id="1"> <Employee Name="Subodh Manas Ashish" /> </TESTCOMPANY> <TESTCOMPANY Name="DEF Corporation" Id="2"> <Employee Name="Niraj Abhijit Manoranjan" /> </TESTCOMPANY> </TestNode>

Value method: This methos is used to fetch the scalar value from the XML instance.
SELECT @TESTXML.value('count(COMPANIES[1]/COMPANY[1]/EMPLOYEE)','VaRCHAR(10)') output 3 SELECT @TESTXML.value('COMPANIES[1]/COMPANY[1]/EMPLOYEE[1]/EMP_ID[1]','INT') output 1

Exist method: It returns a bit value and is used to verify if an XPATH expression is found within an XML instance.
SELECT @TESTXML.exist('/COMPANIES/COMPANY/COMPANY_NAME[.="ABC Corporation"]') output 1 SELECT @TESTXML.exist('/COMPANIES/COMPANY/COMPANY_NAME[.="ABC Corporation"]') output 0

Nodes method: It is used to shred the XML into tabular form.


SELECT EMP.col.query('./EMP_FNAME').value('.','VARCHAR(10)') AS FNAME, EMP.col.query('./EMP_LNAME').value('.','VARCHAR(10)') AS LNAME, EMP.col.query('./EMP_ID').value('.','INT') AS ID FROM @TESTXML.nodes('/COMPANIES/COMPANY/EMPLOYEE') AS EMP(col) output

FNAME Subodh Manas Ashish Niraj Abhijit Manoranjan

LNAME Kant Panda Tondon Choubey Kalita Mohapatra

ID 1 2 3 4 5 6

Subodh Kant Mishra

You might also like