欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL server xml拆分整再整合行简单示例

程序员文章站 2022-03-16 22:56:19
成效结果:with cte as (select C.*,name FROM (select abc00,x.y.value('.', 'VARCHAR(16)') as abc05,KID from (select ABC00, CAST('' + REPLACE(abc05, ',','') + '' as xml ) as KID FROM APP_BUSINESS_CONTRACT where...

成效结果:
SQL server xml拆分整再整合行简单示例

with cte as (
select C.*,name FROM (
select abc00,x.y.value('.', 'VARCHAR(16)') as abc05,KID  from (
select ABC00, CAST('<row>' + REPLACE(abc05, ',','</row><row>') + '</row>' as xml ) as KID FROM APP_BUSINESS_CONTRACT  where  abc00=11389 ) as c
CROSS APPLY KID.nodes('row') x(y) 
) 
AS C 
left join APP_BASE_PRODUCT  B on B.abp00 = C.abc05) 

select c.abc00,abc05,STUFF((SELECT ',' + b.name FROM cte b  WHERE b.abc00 = c.abc00 FOR XML PATH('')), 1, 1, '') newname FROM APP_BUSINESS_CONTRACT c
WHERE abc00=11389

关键数据表结构
APP_BUSINESS_CONTRACT合同表(ABC00 合同id,ABC05 产品线id)
APP_BASE_PRODUCT(ABP00 产品线id,name 产品线名称)
此处仅取一条作用例
SQL server xml拆分整再整合行简单示例
本人sql基础较为薄弱,仅看网上案例及说明完成sql,部分说明有误的地方欢迎指正
思路:讲合同表的产品线id拆分为列,然后与产品线表一一匹配后,再将多行合并为一行再进行整合显示,主要需要再1,2两个位置的数据操作
SQL server xml拆分整再整合行简单示例
第一步,拆分
SQL server xml拆分整再整合行简单示例
参考- - -XML基础操作方法
参考- - -CROSS APPLY 使用说明
1.通过replace、cast把abc05转成XML的形式KID字段(如上图示KID列,row或者其他标签都行)
2.KID.nodes(‘row’) x(y) 对XML执行替换row标签的值返回为x(y)”列“
通过xml.nodes x(y) 方法能将xml转化为列表 x(y)
3.通过x.y.value 获取x(y)列的值
xml.value 方法可以获取对应该项值
4. 通过CROSS APPLY 循环 第3步,最后得到上图

左连接关联产品线表后用cte对返回表做一个封装,看起来好看点免得把自己绕晕,后面就可以把cte当作结果集的临时表使用

with cte as (
select C.*,name FROM (
select abc00,x.y.value('.', 'VARCHAR(16)') as abc05,KID  from (
select ABC00, CAST('<row>' + REPLACE(abc05, ',','</row><row>') + '</row>' as xml ) as KID FROM APP_BUSINESS_CONTRACT  where  abc00=11389 ) as c
CROSS APPLY KID.nodes('row') x(y) ) AS C 
left join APP_BASE_PRODUCT  B on B.abp00 = C.abc05
) 

第二部以原合同表为基础表把封装好的结果集多行根据id整合到一行
STUFF简单用法

select c.abc00,abc05,
STUFF((SELECT ',' + b.name FROM cte b  WHERE b.abc00 = c.abc00 FOR XML PATH('')), 1, 1, '') newname 
 FROM APP_BUSINESS_CONTRACT c
 WHERE abc00=11389

连同上面的cte 一起运行结果就是一开始显示的结果了,代码上面有
SQL server xml拆分整再整合行简单示例

本文地址:https://blog.csdn.net/qq_38333529/article/details/107667426

相关标签: Sql server