Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

sql server 2005 - error in creating a temp table using dynamic sql

declare @TableName nvarchar(max)
set @TableName='addresses'

DECLARE @sql NVARCHAR(MAX)
set @sql= 'create table #tempadd ( '
SELECT @sql=@sql + STUFF( -- Remove first comma  
(  
 SELECT  ', ' + column_name+' '+ case when DATA_TYPE='varchar' then DATA_TYPE +'(500)' else DATA_TYPE end   FROM -- create comma separated values  
 (  
   SELECT column_name,DATA_TYPE FROM information_schema.columns  where table_name = @TableName --Your query here  
 ) AS T FOR XML PATH('')  
)  
,1,1,'')  

set @sql =@sql+' ) '


print @sql 

--SET @sql='SELECT * into #tempadd FROM '+@TableName+  ' WHERE 1=2'


EXEC sp_executesql @sql

select * from #tempadd

This results in an error:

Msg 208, Level 16, State 0, Line 25
Invalid object name '#tempadd'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your temp table is limited to the scope of your dynamic query since it is defined within.

You could add your select * from #tempadd statement to the end of your @sql query. Alternatively I think you can define #tempadd before your dynamic query and it should be accessible, but I'm not certain on that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...