T-SQL XML to retrieve attribute value and the respective element value

1.1k Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER
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)