简体   繁体   中英

Transform XML data into Tabular format in T-SQL

I would like to know how I could transform XML hierarchical data into tabular format and join with other relational database tables in SQL Server 2005 T-SQL (XPath/XQuery).

For instance,

<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

Thanks for your suggestion. :)

Here's one way:

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)

Here is a slight variation on the answer Joe submitted earlier:

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])

This was done in MSSQL Server 2008 R2

Reference Site

I hopes this one helps you

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM