2016-03-03 42 views
0

我正在嘗試將動態表名稱加載到本地表中。從我找到的例子看起來很簡單,但是我收到一條錯誤消息。 - >'#outtbl_15133897'附近的語法不正確SQL - 使用sp_executesql輸出動態表名稱

希望另一組眼睛能看到我失蹤的東西。由於

DECLARE @OutTbl TABLE (Name varchar(100), type varchar(20), row int); 
DECLARE @curName as NVARCHAR(MAX); 

DECLARE @sqlCommand as NVARCHAR(MAX); 
SET @curName = '#outtbl_' + LEFT(replace(replace(CONVERT (time, GETDATE()),':',''),'.',''),8); 

SET @sqlCommand = 'CREATE TABLE #OutTbl (Name varchar(100), type varchar(20), row int); ' 
+ 'INSERT INTO #outtbl SELECT c.Name,c.Type, ROW_NUMBER() OVER(ORDER BY c.QueryID,c.GroupID,c.ColumnID) as row ' 
+ 'FROM MYDB.dbo.DynamicReport_Columns c ' 
+ 'INNER JOIN MYDB.dbo.DynamicReport_Tables t on t.TableID = c.TableID ' 
+ 'WHERE c.QueryID=1 and c.GroupID=1 and IsOutput <> ''N'';'; 
SET @curName = @curName + ' TABLE OUTPUT'; 
EXEC sys.sp_executesql @sqlCommand,@curName,@OutTbl output 

回答

-1

我不是這個100%...我想我也有類似的問題,但我通過使臨時表全局臨時表...... ## outtbl

+0

我解決了它會避免全局臨時表。他們有一些問題,。他們可用於任何連接,所以併發性是一場噩夢 –

+0

提供一個建議......因爲我也想知道一個更有效的方法。我查閱了使用全局臨時表編寫的程序,並將其切換爲本地臨時表。我收到了與上面相同的錯誤,但適用於全局臨時表。 – manderson

+0

這是關於上述問題的更多信息。 http://stackoverflow.com/questions/662049/dynamic-sql-results-into-temp-table-in-sql-stored-procedure – manderson