sql语法-表A如何由表B对应相同的值做转换
请教表A如何由表B对应相同的值做转换:
表A:
A1 (1) (2) (3) (1,2),(2,3) (1,2,3)
B1 (3) (6) (8) (3,6),(6,8) (3,6,8)
C1 (3) (6) (3,6)
…
表B:
(1) a
(2) b
(3) c
(6) d
(8) e
(1,2) f
(2,3) g
(3,6) h
(6,8) i
(1,2,3) j
(3,6,8) k
…
结果:
A1 a b c f,g j
B1 c d e h,i k
C1 c d h
------解决方案--------------------create function wsp(@c varchar(50))
returns varchar(50)
as
begin
if(len(@c)=0)
return ' '
else
begin
declare @star int
declare @end int
declare @s varchar(50)
declare @r varchar(50)
set @star=1
set @r= ' '
while charindex( '( ',@c)> 0
begin
set @s=substring(@c,1,charindex( ') ',@c))
select @r=@r+ ', '+c2 from t2 where t2.c1=@s
set @star=charindex( ') ',@c)+1
set @c=substring(@c,@star+1,len(@c))
end
set @r=right(@r,len(@r)-1)
end
return @r
end
select c1,dbo.wsp(c2) as c2,dbo.wsp(c3) as c3,dbo.wsp(c4) as c4,dbo.wsp(c5) as c25,dbo.wsp(c6) as c6 from t1
------解决方案----------------------原始数据:@A
declare @A table(ID varchar(2),I1 varchar(3),I2 varchar(3),I3 varchar(5),I4 varchar(11),I5 varchar(100))
insert @A
select 'A1 ', '(1) ', '(2) ', '(3) ', '(1,2),(2,3) ', '(1,2,3),(2,3,4) ' union all
select 'B1 ', '(3) ', '(6) ', '(8) ', '(3,6),(6,8) ', '(3,6,8) ' union all
select 'C1 ', '(3) ', '(6) ', ' ', '(3,6) ', ' '
--原始数据:@B
declare @B table(I varchar(7),No varchar(1))
insert @B
select '(1) ', 'a ' union all
select '(2) ', 'b ' union all
select '(3) ', 'c ' union all
select '(6) ', 'd ' union all
select '(8) ', 'e ' union all
select '(1,2) ', 'f ' union all
select '(2,3) ', 'g