--有两种方法,第一种是用游标(建film表和演员临时表占的内容比较多)
if exists (select * from sysobjects where name='film' and type='U')
drop table film ----建立film表,插入两行数据导演为Joson
create table film (film_id varchar(10),film_name varchar(32),actor varchar(1024),derector varchar(10))
insert into film
select '0001','film1','Jane,Tony,sun' ,'Joson'
union select '0002','film2','Jane,Tony,Jim,Lucy','Joson'
if exists (select * from sysobjects where name='actor' and type='U')
drop table actor
create table actor
(actor varchar(32))
declare @lsactor varchar(1024) ,@ldactor varchar(32),@lsderector varchar(10)
set @lsderector='Joson' --
declare cursor_test cursor for select actor from film where derector=@lsderector
open cursor_test
fetch next from cursor_test into @lsactor
while @@fetch_status=0
begin
while charindex(',',@lsactor,1)>0
begin
set @ldactor=substring(@lsactor,1,charindex(',',@lsactor,1)-1)
set @lsactor=substring(@lsactor,charindex(',',@lsactor,1)+1,len(@lsactor)-charindex(',',@lsactor,1))
insert into actor select @ldactor
if charindex(',',@lsactor,1)=0
begin
set @ldactor=@lsactor
insert into actor select @ldactor
end
end
fetch next from cursor_test into @lsactor
end
close cursor_test
deallocate cursor_test
select * from film
select distinct actor from actor
附上film表和导演为Josn合作过的演员结果
另外一种方法不用游标,看起来比较简单
if exists (select * from sysobjects where name='film' and type='U')
drop table film ----建立film表,插入两行数据导演为Joson
create table film (film_id varchar(10),film_name varchar(32),actor varchar(1024),derector varchar(10))
insert into film
select '0001','film1','Jane,Tony,sun' ,'Joson'
union select '0002','film2','Jane,Tony,Jim,Lucy','Joson'
if exists (select * from sysobjects where name='actor' and type='U')
drop table actor
create table actor
(actor varchar(32))
declare @lsactor varchar(1024) ,@ldactor varchar(32),@lsderector varchar(10)
set @lsderector='Joson' --导演为Joson
set @lsactor=''
select @lsactor +=actor+',' from film where derector=@lsderector
set @lsactor=substring(@lsactor,1,len(@lsactor)-1)
begin
while charindex(',',@lsactor,1)>0
begin
set @ldactor=substring(@lsactor,1,charindex(',',@lsactor,1)-1)
set @lsactor=substring(@lsactor,charindex(',',@lsactor,1)+1,len(@lsactor)-charindex(',',@lsactor,1))
insert into actor select @ldactor
if charindex(',',@lsactor,1)=0
begin
set @ldactor=@lsactor
insert into actor select @ldactor
end
end
select * from film
select distinct actor from actor
end
这两种方法结果是一样的