使用动态SQL创建临时表时出错 [英] error in creating a temp table using dynamic sql

查看:267
本文介绍了使用动态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

这将导致错误:


消息208,级别16,状态0,行25

无效的对象名称' #tempadd'。

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


推荐答案

您的临时表已在其中定义,因此仅限于动态查询的范围。

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

您可以将#tempadd 语句中的 select *添加到 @的末尾sql 查询。另外,我认为您可以在动态查询之前定义#tempadd,并且应该可以访问它,但是我不确定。

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.

这篇关于使用动态SQL创建临时表时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆