Skip to content

Instantly share code, notes, and snippets.

@okaram
Last active December 29, 2015 05:39
Show Gist options
  • Save okaram/7623953 to your computer and use it in GitHub Desktop.
Save okaram/7623953 to your computer and use it in GitHub Desktop.
XML SQL Queries
WITH
PeopleAndSkills AS (
SELECT P.*,
cast(Skill.query('./text()') as varchar) as SkillName,
Skill.value('(./@level)[1]' ,'varchar(20)') as SkillLevel
FROM People P CROSS APPLY SkillsXml.nodes('/skills/skill') as Skills(Skill)
)
SELECT * from PeopleAndSkills
WHERE SkillLevel='Medium'
SELECT P.*, Skill.query('.')
FROM People P CROSS APPLY SkillsXml.nodes('/skills/skill') as Skills(Skill)
SELECT id,name, SkillsXml.query('/skills/skill[1]')
FROM People
CREATE TABLE People (
id int primary key,
name varchar(20),
SkillsXml xml
);
INSERT INTO People(id,name,SkillsXml) VALUES(1,'Orlando',
'<skills>
<skill level="High">SQL</skill>
<skill level="Medium">C#</skill>
</skills>');
INSERT INTO People(id,name,SkillsXml) VALUES(2,'Lina',
'<skills>
<skill level="Low">SQL</skill>
<skill level="Medium">Java</skill>
</skills>');
SELECT id,name, SkillsXml.value('(/skills/skill[1]/@level)[1]','varchar(10)')
FROM People
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment