在SQL Server中迭代XML变量是否是XML中的内容

时间:2014-08-18 04:53:16

标签: sql xml xquery

在SQL Server中,如何查询以下XML

<Employee>
   <FirstName>David</FirstName>
   <LastName>Jons</LastName>
   <Age>28</Age>
</Employee>
<Employee>
   <FirstName>Eric</FirstName>
   <LastName>Terry</LastName>
   <Age>36</Age>
</Employee>
<Employee>
   <FirstName>Kady</FirstName>
   <LastName>Campell</LastName>
   <Age>21</Age>
</Employee>

如果元素名称相同,我们可以使用以下方法:

Iterate through XML variable in SQL Server

因此,如何获得以下结果:

FirstName   |  LastName   | Age
----------- +-------------+-----
David       |   Jons      | 28
Eric        |   Terry     | 36
Kady        |   Campell   | 21

鉴于我不知道XML的元素名称,如FisrtName,LastName,Age,

我想我希望得到像这样的SQL语句的结果:

SELECT * FROM Employee

其中我不知道表Employee

的列名

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

DECLARE @input XML = '<Employee>
   <FirstName>David</FirstName>
   <LastName>Jons</LastName>
   <Age>28</Age>
</Employee>
<Employee>
   <FirstName>Eric</FirstName>
   <LastName>Terry</LastName>
   <Age>36</Age>
</Employee>
<Employee>
   <FirstName>Kady</FirstName>
   <LastName>Campell</LastName>
   <Age>21</Age>
</Employee>'

SELECT
    FirstName = xc.value('(FirstName)[1]', 'varchar(50)'),
    LastName = xc.value('(LastName)[1]', 'varchar(50)'),
    Age = xc.value('(Age)[1]', 'int')
FROM
    @input.nodes('/Employee') AS XT(XC)

那应该给你一个输出:

FirstName   LastName    Age
---------------------------
David       Jons         28
Eric        Terry        36
Kady        Campell      21