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   
             

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值