2

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. :)

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
Thurein
  • 2,536
  • 7
  • 34
  • 49

3 Answers3

4

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)
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
1

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

Demitrius Nelon
  • 1,210
  • 1
  • 10
  • 29
0

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
wizzardz
  • 5,664
  • 5
  • 44
  • 66
  • This older method is less efficient and generally performs worse than the technique given in the other two answers. – Joe Stefanelli Dec 23 '10 at 15:44
  • Yes. I've seen several cases where I've been able to improve performance by replacing your method with the newer one. It gets even worse when you run into a situation where a developer has forgotten the `sp_xml_removedocument`. – Joe Stefanelli Dec 23 '10 at 15:49
  • @Joe: thanks Joe,I was using this sp im most palaces,I think its better chance them now. +1 for your answer :) – wizzardz Dec 23 '10 at 15:55