作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] XML 用node name筛选?
时间Fri Feb 23 16:24:36 2018
我参考以下网站来达成你要的:
1. sql xml 入门:xpath和xquery:
https://goo.gl/EQ2XiF
2. 节点的本机名称的函式
https://goo.gl/LusmLN
3. Removing XML tags from FOR XML PATH
https://goo.gl/M7Ufz9
----------------------
SQL 如下:
;with tb1 as (
select tab.col.value('../@id','int') as 'id',
tab.col.query('.') as content
from @xml.nodes('/row/*') as tab(col)
inner join table t1
on tab.col.value('local-name(.)','varchar(100)') = t1.cola
),
tb2 as (
select t1.id,(
select content as [*] from tb1 where id = t1.id for xml path('')
) as content
from tb1 t1
group by t1.id
)
select id as '@id',cast(content as xml) as [*] from tb2 for xml path('row')
------------------------------------------
想法:
1. 观察 tb1,tb2 就可以知道大概的逻辑了!
2. 想知道还有没有更好的解法,谢谢大家!
※ 引述《YiMMiY (YiMMiY)》之铭言:
: MS SQL - 2012
: 各位版友们好
: 手边有一个XML,如下
: @xml = '
: <row id='1'>
: <AAA>zxc</AAA>
: <BBB>asd</BBB>
: <CCC>qwe</CCC>
: </row>
: <row id='2'>
: <AAA>vbn</AAA>
: <BBB>fgh</BBB>
: <CCC>rty</CCC>
: <DDD>jkl</DDD>
: </row>
: <row id='3'>
: <AAA>sdf</AAA>
: <DDD>xcv</DDD>
: </row>
: '
: 手边还有一个TABLE,如下
: Tb_DEF
: COLA ...
: --------------
: AAA ...
: CCC ...
: 想达到
: <row id='1'>
: <AAA>zxc</AAA>
: <CCC>qwe</CCC>
: </row>
: <row id='2'>
: <AAA>vbn</AAA>
: <CCC>rty</CCC>
: </row>
: <row id='3'>
: <AAA>sdf</AAA>
: </row>
: 也就是TABLE的[COLA]为XML的筛选条件
: 请问该如何下指令呢?谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.223.59.47
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1519374279.A.D1D.html
1F:推 YiMMiY: 大感谢啊啊啊 原本我有做到tb1那边 但tb2那段就做不出来了 02/23 17:57