日期:2014-05-18  浏览次数:20617 次

拼接的字符串成长动态列,通过exec把这些列查询送到临时表问题
SQL code

declare @sql varchar(200)
set @sql = 'select 10 as id  into #t '
exec(@sql)

select * from #t
drop table #t



假设这边的@sql是通过拼接生成的动态列的查询语句,现在想把这个查询语句放到临时表#t里面,但是好像会报错。

------解决方案--------------------
SQL code

select * from (select 10 as id)t  into #t

------解决方案--------------------
不能这样写的.
SQL code
declare @sql varchar(200)
create table #t(id int)
set @sql = 'select 10 as id'
insert into #t exec(@sql)
select * from #t
/*
id
-----------
10

(1 行受影响)

*/
drop table #t

------解决方案--------------------
SQL code
declare @sql varchar(200)
create table #t(id int)
set @sql = 'select 10 as id'
insert into #t exec(@sql)
select * from #t

------解决方案--------------------
1楼不是写给你select ... into ...的用法了么?
探讨
但是前提条件#t表是不知道表结构的,这样做不行了

------解决方案--------------------
SQL code

--写错了,改下,汗
select * into #t from (select 10 as id)t

------解决方案--------------------
SQL code

--我晕,静态的你会了,改动态的不会?
declare @sql varchar(200)
if object_id('#t') is not null drop table #t
set @sql = 'select * into #t from (select 10 as id)t'
exec(@sql)

select * from #t