T-SQL查询XML数据

时间:2013-04-15 21:25:10

标签: sql-server xml tsql

我有以下格式化的XML:

<ROOT>
 <table1>
  <row ID="1".... \>
 </table1>
 <table2>
  <row ID="1".... \>
 </table2>
...
</ROOT>

我想生成一个返回的查询:

TableName
table1
table2 
...

换句话说,

下每个节点的值

1 个答案:

答案 0 :(得分:2)

 DECLARE @data XML;

SET @data = 

N'
<root>
 <table1>
  <row ID="1"/>
 </table1>
 <table2>
  <row ID="1"/>
 </table2>
</root>';


SELECT
    T.myAlias.value('fn:local-name(..)', 'nvarchar(50)') as ParentOf_RowElement_Name
FROM 
    @data.nodes('//row') AS T(myAlias)

;



ParentOf_RowElement_Name
--------------------------------------------------
table1
table2

OR

DECLARE @data XML;

SET @data = 

N'
<root>
 <table1>
  <row ID="1"/>
 </table1>
 <table2>
  <row ID="1"/>
 </table2>
</root>';


SELECT
    T.myAlias.value('fn:local-name(.)', 'nvarchar(50)') as ChildOf_RootElement_Name
FROM 
    @data.nodes('//root/*') AS T(myAlias)
;





ChildOf_RootElement_Name
--------------------------------------------------
table1
table2