0

I am running the below block in sql server 2014 , but it is getting failed with the error -

Must declare the table variable @tname.

Any ideas to fix this error?

DECLARE @IntVariable NVARCHAR(500);  
DECLARE @SQLString NVARCHAR(500);  
DECLARE @ParmDefinition NVARCHAR(500);  
  
/* Build the SQL string one time.*/  
SET @SQLString =  
     N'SELECT * into #t from @tname';  
SET @ParmDefinition = N'@tname NVARCHAR(500)';  
/* Execute the string with the first parameter value. */  
SET @IntVariable = 'tst_tbl';  
EXECUTE sp_executesql @SQLString, @ParmDefinition,  
                      @tname = @IntVariable;
sha12
  • 11
  • 2
  • Note that using a `SELECT ... INTO` into a temporary table is more or less pointless in a dynamic statement unless you are planning to further use it in the same dynamic statement; the temporary table will be dropped automatically as soon as the dynamic statement's scope ends. For example `EXEC sys.sp_executesql N'SELECT name INTO #t FROM sys.databases;'; SELECT name FROM #t;` will generate the error "Invalid object table '#t'." – Thom A Sep 09 '22 at 15:57

0 Answers0