0

我尝试在单引号内创建一个临时表,它显示错误,它无法识别表#newtable......它只支持##table(全局临时表)但我不想要一个全局临时表,我只想知道背后的原因是什么解释请。

 select 
     column1, column2, column3, ##newtable.columnid as ShipProfile,
     row_number() over (order by Id) as ''RowNumber'' 
 into 
     ##TempProduct 
 from 
     Product 
 left join 
     ##newtable on Product.columnId = ##newtable.ColumnId 
 where 
     MerchantId= ' + convert(varchar(20), @MerchantID) 
4

2 回答 2

1

To quote from the famous The Curse and Blessings of Dynamic SQL:

Next thing to observe is that the dynamic SQL is not part of the stored procedure, but constitutes its own scope. Invoking a block of dynamic SQL is akin to call a nameless stored procedure created ad-hoc. This has a number of consequences:

...

  • Temp tables created in the dynamic SQL will not be accessible from the calling procedure since they are dropped when the dynamic SQL exits. (Compare to how temp tables created in a stored procedure go away when you exit the procedure.) The block of dynamic SQL can however access temp tables created by the calling procedure.

So you can either define the temp table (create table #outertemp (col1 INT Primary KEY ...)) in the stored procedure where you execute the string (not in the string itself!) or you can use global temp tables inside your dynamic SQL.

于 2013-01-08T09:01:27.367 回答
-1

您可以create table #outertemp (col1 INT Primary KEY ...))在执行字符串的存储过程中定义临时表(而不是在字符串本身中!),也可以在动态 SQL 中使用全局临时表。

于 2013-06-09T14:22:33.777 回答