我想知道如何将XML分层数据转换为表格格式,并与SQL Server 2005 T-SQL(XPath / XQuery)中的其他关系数据库表连接。
例如,
<Employees>
<Employee ID="001" Name="David" />
<Employee ID="002" Name="Mike" />
<Employee ID="003" Name="Alex" />
<Employee ID="004" Name="Morris" />
</Employees>
To ..
ID Name
--------+--------
001 David
002 Mike
003 Alex
004 Morris
感谢您的建议。 :)
答案 0 :(得分:4)
这是一种方式:
declare @x xml
set @x = '<Employees>
<Employee ID="001" Name="David" />
<Employee ID="002" Name="Mike" />
<Employee ID="003" Name="Alex" />
<Employee ID="004" Name="Morris" />
</Employees>'
select emp.e.value('@ID','varchar(10)') as ID,
emp.e.value('@Name','varchar(10)') as Name
from @x.nodes('Employees/Employee') as emp(e)
答案 1 :(得分:1)
以下是Joe先前提交的答案的略微变化:
DECLARE @X xml
SET @X = '<Employees>
<Employee ID="001" Name="David" />
<Employee ID="002" Name="Mike" />
<Employee ID="003" Name="Alex" />
<Employee ID="004" Name="Morris" />
</Employees>'
SELECT
[Employee].value('@ID','int')As ID,
[Employee].value('@Name','varchar(10)') As Name
FROM
@x.nodes('/Employees/Employee') Employee([Employee])
这是在MSSQL Server 2008 R2中完成的
答案 2 :(得分:0)
我希望这个可以帮助你
declare @xml varchar(max)
SET @xml = '<Employees>
<Employee ID="001" Name="David" />
<Employee ID="002" Name="Mike" />
<Employee ID="003" Name="Alex" />
<Employee ID="004" Name="Morris" />
</Employees>'
Declare @documentHandler INT
EXEC sp_xml_preparedocument @documentHandler OUTPUT,@xml
SELECT *
FROM OPENXML(@documentHandler,'/Employees/Employee')
WITH (ID varchar(20),
Name varchar(150))
EXEC sp_xml_removedocument @documentHandler