表内容如下a,U_ID相同的将 R_MOdule字段中相同部分取出来,并逗号割开(这里就是第一第二行),
如果以逗号格开的字符串相同就提取出来,也就是要得到b表的意思。
a
U_ID R_MOdule
----------- --------------------------------------------------
4 8,9,10,11,12,15,16,17,18,19,20,21,22,23,24,25,28
4 1,8,14,18
8 1,8,14,18
b
U_ID R_Module
4 8,18
8 1,8,14,18
答案内详细!
create table tb(U_ID int,R_MOdule varchar(8000))
insert tb select 4,'8,9,10,11,12,15,16,17,18,19,20,21,22,23,24,25,28'
union all select 4,'1,8,14,18'
union all select 4,'1,8,14,18,17'
union all select 8,'1,8,14,18'
go
--合并数据增加的辅助表
select top 8000 id=identity(int) into 序数表 from syscolumns a,syscolumns b
go
--合并处理函数
create function f_merg(@U_ID int)
returns varchar(8000)
as
begin
declare @s nvarchar(4000)
set @s=''
select @s=@s+','+s
from(
select top 100 percent
s=substring(a.R_MOdule,b.id,charindex(',',a.R_MOdule+',',b.id)-b.id)
from tb a,序数表 b
where a.U_ID=@U_ID and b.id<=len(a.R_MOdule) and substring
(','+a.R_MOdule,b.id,1)=','
group by substring(a.R_MOdule,b.id,charindex(',',a.R_MOdule+',',b.id)-b.id)
having count(*)=(select count(*) from tb where U_ID=@U_ID)
order by min(id))a
return(stuff(@s,1,1,''))
end
GO
--调用函数进行处理
select U_ID,R_MOdule=dbo.f_merg(U_ID) from tb group by U_ID
go
--删除测试
drop table tb,序数表
drop function f_merg
--运行结果:
U_ID R_Module
4 8,18
8 1,8,14,18
原帖地址:http://community.csdn.net/Expert/topic/3841/3841961.xml?temp=.6100428