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

不能动态生成临时表?
SQL code

DECLARE @sql nvarchar(2000)
SET @sql='CREATe TABLE #tempdisp (rowNO int,goodID int,haveLast int,storageID int)'
exec(@sql)
select * from  #tempdisp 
DROP TABLE #tempDisp



结果
消息 208,级别 16,状态 0,第 4 行
对象名 '#tempdisp' 无效。

SQL code

DECLARE @sql nvarchar(2000)
--SET @sql='
CREATe TABLE #tempdisp (rowNO int,goodID int,haveLast int,storageID int)
--'
--exec(@sql)
select * from  #tempdisp 
DROP TABLE #tempDisp


直接生成的完全没有问题,何解?

------解决方案--------------------
#这个临时表有作用域的,exec外不能使用。
##两个井号是全局临时表,可以使用。

SQL code


DECLARE @sql nvarchar(2000)
SET @sql='CREATe TABLE ##tempdisp (rowNO int,goodID int,haveLast int,storageID int)'
exec(@sql)
select * from  ##tempdisp 
DROP TABLE ##tempDisp

------解决方案--------------------
可以考虑下用 别的临时表代替
类似 嵌套查询 或者把 CTE 当临时表使用.
------解决方案--------------------
SQL code
DECLARE @sql nvarchar(2000)
SET @sql='
CREATe TABLE #tempdisp (rowNO int,goodID int,haveLast int,storageID int)
select * from #tempdisp 
DROP TABLE #tempDisp
'
exec(@sql)