0

I have an XML column in a table. This column is called UserDef. The Xml looks like this:

<UserDefs>
    <UserDef id="EmpNum">002</UserDef>
    <UserDef id="EmpDept">AUT</UserDef>
    <UserDef id="EmpName">XYZ ABC</UserDef>
    <UserDef id="EmpHireDate">2009-11-01T23:59:00-06:00</UserDef>
</UserDefs>

What should the query look like to return a result like this:

Column1     Column2 
--------------------
EmpNum      002
EmpDept     AUT
EmpName     XYZ ABC
EmpHireDate 2009-11-01 23:59:00

Thank you.

1 Answer 1

1
declare @xml xml
set @xml = '<UserDefs>
            <UserDef id="EmpNum">002</UserDef>
            <UserDef id="EmpDept">AUT</UserDef>
            <UserDef id="EmpName">XYZ ABC</UserDef>
            <UserDef id="EmpHireDate">2009-11-01T23:59:00-06:00</UserDef>
            </UserDefs>'

select R.nref.value('./@id[1]','nvarchar(200)') as Column1,
   R.nref.value('./text()[1]','nvarchar(200)') as Column2
from @xml.nodes('/UserDefs/*') R(nref);

consider to use proper length for varchar/nvarchar type for your real data and also you will need to convert date value properly

if we need to select from table:

declare @xml xml
set @xml = '<UserDefs>
        <UserDef id="EmpNum">002</UserDef>
        <UserDef id="EmpDept">AUT</UserDef>
        <UserDef id="EmpName">XYZ ABC</UserDef>
        <UserDef id="EmpHireDate">2009-11-01T23:59:00-06:00</UserDef>
        </UserDefs>'

declare @txml table(UserDef xml)
insert into @txml values (@xml);

select 
a.value('./@id[1]','nvarchar(200)') as Column1,
a.value('./text()[1]','nvarchar(200)') as Column2
from @txml 
CROSS APPLY UserDef.nodes('/UserDefs/*') AS tbl(a)
Sign up to request clarification or add additional context in comments.

1 Comment

I need to get the value from an xml column of a table. How do I adapt your snippet to query from a table instead of an XML variable ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.