Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Created August 22, 2020 05:01
Show Gist options
  • Save joe-oli/e410f7af5d16c7d9999a8139aaa8e4a1 to your computer and use it in GitHub Desktop.
Save joe-oli/e410f7af5d16c7d9999a8139aaa8e4a1 to your computer and use it in GitHub Desktop.
snippets for tsql that deals with xml
-- T-SQL, XQuery, XML stuff quick ref
declare @xml xml = N'
<root>
<node roll="1" fname="sid">Luke Skywalker</node>
<node roll="2" fname="neel">Anakin Skywalker?<node>
</root>'
-- prints the roll number of the first node
select @xml.value('(/root/node/@roll)[1]', 'INT')
-- prints the text of the second node
select @xml.value('(/root/node)[2]', 'VARCHAR(40)')
-- prints the node text and attribute values of the node which has roll = 2
select
xmldata.col.value('@roll', 'int'),
xmldata.col.value('@fname', 'varchar(10)'),
xmldata.col.value('.', 'varchar(20)')
from
@xml.nodes('(/root/node)') xmldata(col)
where
xmldata.col.value('@roll', 'int') = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment