Sql Server: Select or Read XML Column Data from table

Introduction:  In this article I am going to share how to parse and read data from XML data type column of sql server table.


Select or Read XML Column Data from table in sql server


Implementation: Let’s create an employee table using table variable for demonstration purpose and insert some dummy data along with xml data in xml type column of table.

DECLARE @Employee TABLE(EmployeeId INT, Age INT, empXML XML)

INSERT INTO @Employee(EmployeeId, Age, empXML) VALUES(101,22,'<ROOT><Employee Country="India" State="Haryana" City="Hissar" /></ROOT>')
INSERT INTO @Employee(EmployeeId, Age, empXML) VALUES(102,25,'<ROOT><Employee Country="India" State="Punjab" City="Patiala" /></ROOT>')
INSERT INTO @Employee(EmployeeId, Age, empXML) VALUES(103,32,'<ROOT><Employee Country="India" State="Maharashtra" City="Mumbai" /></ROOT>')
INSERT INTO @Employee(EmployeeId, Age, empXML) VALUES(104,21,'<ROOT><Employee Country="India" State="Himachal" City="Shimla" /></ROOT>')

Check table data
SELECT * FROM @Employee

Now the query to read data from XML column and select as table will be as:

SELECT EmployeeId, Age,
col.value('@Country','VARCHAR(100)') AS Country,
col.value('@State','VARCHAR(100)') AS State,
col.value('@City','VARCHAR(100)') AS City
FROM @Employee
CROSS APPLY empXML.nodes('ROOT/Employee') tab(col);

Check updated table data now
SELECT * FROM @Employee

Result will be as shown in image above.

  Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..