0

我在表中有一个 XML 列。此列称为 UserDef。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>

返回如下结果的查询应该是什么样子:

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

谢谢你。

4

1 回答 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);

考虑为您的真实数据使用适当的 varchar/nvarchar 类型长度,并且您还需要正确转换日期值

如果我们需要从表中选择:

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)
于 2013-07-10T01:38:43.983 回答