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

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

3 Comments

This older method is less efficient and generally performs worse than the technique given in the other two answers.
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: thanks Joe,I was using this sp im most palaces,I think its better chance them now. +1 for your answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.