简体   繁体   中英

SQL - Dynamic table name output with sp_executesql

I'm trying to load a dynamic table name in to a local table. Seems simple enough from the examples I've found, however I'm getting an error message. -> Incorrect syntax near '#outtbl_15133897'

Hopefully, another set of eyes can see what I'm missing. Thanks

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

我不是100%对此...我想我也有类似的问题,但是我通过使temp表成为全局temp表来解决了它。## outtbl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM