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)