根据表1某字段内容(1,2,3之类),显示对应表2的内容
数据库SQL SERVER 2000 SP4
create table 表1(ID int, NAME varchar(10),LESSON varchar(10))
insert into 表1 values(1,'b','1,2,3')
insert into 表1 values(2,'bb','4')
insert into 表1 values(3,'bbb','5')
go
create table 表2(ID int, NAME varchar(10))
insert into 表2 values(1, 'aa')
insert into 表2 values(2, 'aaa')
insert into 表2 values(3, 'aaaa')
go
表1 LESSON字段内容是1,2,3之类的,对应的是表2 ID字段,可包含多个表2 ID,现要求显示表1全部内容,LESSON字段显示表2 NAME内容,如下
ID NAME LESSON
1 b aa,aaa,aaaa
具体要怎么实现,请各位帮帮忙,谢谢。
[解决办法]
look look
修改成你自己想要的
create table #t1(ID int, NAME varchar(10),LESSON varchar(10))
insert into #t1 values(1,'b','1,2,3')
insert into #t1 values(2,'bb','4')
insert into #t1 values(3,'bbb','5')
go
create table #t2(ID int, NAME varchar(10))
insert into #t2 values(1, 'aa')
insert into #t2 values(2, 'aaa')
insert into #t2 values(3, 'aaaa')
go
select t1.*,
(select t.NAME+','
from #t2 t
where ','+CAST(t1.LESSON as varchar)+',' like '%,'+cast(t.ID as varchar)+',%'
for xml path('')) as LESSONs
from #t1 t1
drop table #t1
drop table #t2
create table #t1(ID int, NAME varchar(10),LESSON varchar(10))
insert into #t1 values(1,'b','1,2,3')
insert into #t1 values(2,'bb','4')
insert into #t1 values(3,'bbb','5')
go
create table #t2(ID int, NAME varchar(10))
insert into #t2 values(1, 'aa')
insert into #t2 values(2, 'aaa')
insert into #t2 values(3, 'aaaa')
go
if(object_id('tempdb..#t') is not null) drop table #t;
create table #t(ID int, NAME varchar(10),LESSON varchar(10),LessonName varchar(1000));
declare tb cursor local
for
select id,name,lesson from #t1
declare @id int,@name varchar(10),@lesson varchar(10),@LessonName varchar(1000)
open tb
fetch tb into @id,@name,@lesson
while(@@fetch_status=0)
begin
set @LessonName=''
select @LessonName= isnull(@LessonName,'')+','+NAME from #t2
where charindex(convert(varchar(20),id),@lesson,1)>0
if isnull(@LessonName,'')<>''
set @LessonName=stuff(@LessonName,1,1,'')
insert into #t(ID , NAME ,LESSON,LessonName)
select @id ,@name ,@lesson ,@LessonName
fetch tb into @id,@name,@lesson
end
close tb
deallocate tb
select *
from #t
set @c1='declare @c11 varchar(1000) set @c11=''''
select @c11=@c11+case when @c11='''' then '''' else '','' end+name from #t2 where id in ('+
(select cresult from #T4)+')'+'select @c11'
delete from #T4
insert into #T4 exec(@c1)
set @c1='insert #t3 select id,name,(select * from #T4) from #t1 where id='+cast(@i1 as varchar)
exec(@c1)
set @i1=@i1+1
end
select * from #T3
--where LESSON<>''