2013-07-09 60 views
0

我在表中有一個XML列。該列被稱爲UserDef。在XML看起來是這樣的:用於檢索屬性值和相應元素值的T-SQL 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 

謝謝。

回答

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) 
+0

我需要從表格的xml列中獲取值。如何使您的片段適合從表中查詢而不是使用XML變量? – FMFF

+1

增加了表格的例子 – sqladmin