表A
id name
1 小明
2 小刚
3 小刘
4 小王表B
id class nameid
1 打篮球 1,2,3,
2 踢足球 2,3,4,
3 打兵乓球 1,3,4,
求出打篮球,踢足球,打兵乓球的人名,如下
1 打篮球 小明,小刚,小刘
2 踢足球 小刚,小刘,小王
3 打兵乓球 小明,小刘,小王
id name
1 小明
2 小刚
3 小刘
4 小王表B
id class nameid
1 打篮球 1,2,3,
2 踢足球 2,3,4,
3 打兵乓球 1,3,4,
求出打篮球,踢足球,打兵乓球的人名,如下
1 打篮球 小明,小刚,小刘
2 踢足球 小刚,小刘,小王
3 打兵乓球 小明,小刘,小王
然后
select id,class,函数(nameid) from 表B
insert into t
select 1, '小明'union all
select 2, '小刚'union all
select 3, '小刘'union all
select 4, '小王'
create table t1(id int, class varchar(10),nameid varchar(10))
insert into t1
select 1, '打篮球','1,2,3' union all
select 2, '踢足球','2,3,4' union all
select 3, '打兵乓球','1,3,4'alter function tr_1(@name varchar(10))
returns varchar(100)
as
begin
declare @str varchar(100)
select @str=isnull(@str,'')+','+name from t where charindex(cast(id as varchar(5)),@name)>0
return stuff(@str,1,1,'')
end
select id,class,dbo.tr_1(nameid) name from t1
if not object_id('ta') is null
drop table ta
Go
Create table ta([id] int,[name] nvarchar(2))
Insert ta
select 1,N'小明' union all
select 2,N'小刚' union all
select 3,N'小刘' union all
select 4,N'小王'
Go
if not object_id('tb') is null
drop table tb
Go
Create table tb([id] int,[class] nvarchar(4),[nameid] nvarchar(6))
Insert tb
select 1,N'打篮球',N'1,2,3,' union all
select 2,N'踢足球',N'2,3,4,' union all
select 3,N'打兵乓球',N'1,3,4,'
Go
Select b.ID,
b.[class],
[nameid]=stuff((select ','+[name]
from ta a
where charindex(','+ltrim(a.id)+',',','+b.[nameid]+',')>0
for xml path('')),1,1,'')
from tb b
/*
ID class nameid
----------- ----- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 打篮球 小明,小刚,小刘
2 踢足球 小刚,小刘,小王
3 打兵乓球 小明,小刘,小王(3 個資料列受到影響)*/