declare @sql varchar(8000) select @sql=字段值 from 表 where 条件 exec(@sql)
例:declare @t table(id int,sql varchar(8000)) insert into @t select 1,'select * from sysobjects where xtype=''u'''declare @sql varchar(8000) select @sql=sql from @t where id=1 exec(@sql)
--用游标实现drop table tbtest go create table tbtest(id int,sql varchar(8000)) insert into tbtest select 1,'select id from sysobjects where xtype=''u''' union all select 2,'select name from sysobjects where xtype=''u'''create table #t1(id int) create table #t2(name varchar(255)) declare @sql varchar(8000) declare @id int declare cur_tmp cursor for select id,sql from tbtest open cur_tmp fetch next from cur_tmp into @id,@sql while @@fetch_status=0 begin if @id=1 begin insert into #t1 --存储exec的结果 exec(@sql) select * from #t1 end if @id=2 begin insert into #t2 --存储exec的结果 exec(@sql) select * from #t2 end fetch next from cur_tmp into @id,@sql end close cur_tmp deallocate cur_tmp
select @sql=字段值 from 表 where 条件
exec(@sql)
insert into @t
select 1,'select * from sysobjects where xtype=''u'''declare @sql varchar(8000)
select @sql=sql from @t where id=1
exec(@sql)
go
create table tbtest(id int,sql varchar(8000))
insert into tbtest
select 1,'select id from sysobjects where xtype=''u'''
union all select 2,'select name from sysobjects where xtype=''u'''create table #t1(id int)
create table #t2(name varchar(255))
declare @sql varchar(8000)
declare @id int
declare cur_tmp cursor for
select id,sql from tbtest
open cur_tmp
fetch next from cur_tmp into @id,@sql
while @@fetch_status=0
begin
if @id=1
begin
insert into #t1 --存储exec的结果
exec(@sql)
select * from #t1
end
if @id=2
begin
insert into #t2 --存储exec的结果
exec(@sql)
select * from #t2
end
fetch next from cur_tmp into @id,@sql
end
close cur_tmp
deallocate cur_tmp