SQL SERVER 2008取出XML数据

用SQL SERVER 2008的for xml可以读取数据并转为XML,下面例程使用了pubs数据库

DECLARE @idoc int
DECLARE @doc varchar(1000) 
set @doc='
  <ROOT>
    <authors>
        <au_id>172-32-1176</au_id>
        <au_lname>White</au_lname>
        <au_fname>Johnson</au_fname>
        <phone>408 496-7223</phone>
        <address>1010932 Bigger Rd.</address>
        <city>Menlo Park</city>
        <state>CA</state>
        <zip>94025</zip>
        <contract>1</contract>
        <books>
            <title>My Book1</title>
            <title>My Book2</title>
        </books>
    </authors>
    <authors>
        <au_id>213-46-8915</au_id>
        <au_lname>Green</au_lname>
        <au_fname>Marjorie</au_fname>
        <phone>415 986-7020</phone>
        <address>309 St. #31</address>
        <city>Boston</city>
        <state>CA</state>
        <zip>94618</zip>

        <contract>1</contract>
        <books>
            <title>My Book3</title>
            <title>My Book4</title>
        </books>
    </authors>
</ROOT>    '

exec sp_xml_preparedocument @idoc OUTPUT,@doc

select a.title,a.au_lname,p.pub_name,p.city
 from  openxml(@idoc,'/ROOT/authors/books',2) 
        WITH(title  varchar(20) './title',
             au_id  varchar(11) '../au_id',
             au_lname varchar(40) '../au_lname',
             au_fname varchar(20) '../au_fname',
             phone varchar(12) '../phone',
             city varchar(20) '../city') As a 
 inner join publishers as p  
   ON a.city=p.city             
   
use pubs
go
select * from authors for xml raw   

select * from authors for xml auto

select publishers.pub_name,titles.title,titles.price 
  from titles,publishers where publishers.pub_id=titles.pub_id
  for xml auto


select 1 As Tag,null as parent,
  authors.au_fname as [Authors!1!au_fname!element],
  authors.au_lname as [Authors!1!au_lname!element],
  NULL AS [Titleauthor!2!Royaltyper],
  NULL AS [Titles!3!au_fname!element]  
FROM  
  authors
UNION ALL
select 2 As Tag,1 as parent,
  au_fname,au_lname,royaltyper,NULL 
from authors inner join titleauthor on 
authors.au_id=titleauthor.au_id  

union all    
select 3 As Tag,2 as parent,
  au_fname,au_lname,royaltyper,title  
from authors inner join titleauthor on 
authors.au_id=titleauthor.au_id inner join titles on 
titles.title_id=titleauthor.title_id   
order by [Authors!1!au_fname!element],[Authors!1!au_lname!element],
   [Titleauthor!2!Royaltyper],tag 
for xml explicit   
             
原文地址:https://www.cnblogs.com/djcsch2001/p/2764574.html