0

I want to be able to pass a parameter to a Query to give the names of the tables I am using.

DECLARE @ImportedTable char(100) 
DECLARE @EnvTable char(100) 

SET @ImportedTable = 'tmpImported'
SET @EnvTable = 'tblDestination'

PRINT @ImportedTable

Select *

From @ImportedTable

When I print the Variable, it looks fine, but when I run the whole thing, the From Clause gives the following error

Must declare the table variable "@ImportedTable".

Why won't it see the variable contents in From Clause?

ScottUK
  • 53
  • 7

1 Answers1

1

As stated, you need dynamics SQL. Something like:

Declare @EnvTable sysname;
Declare @sql nvarchar(max);
Set @ImportedTAble = 'tmpImported'
Set @EnvTable = 'tblDestination'
Set @sql = N'Select * From ' + QUOTENAME(@ImportedTable);

Exec sp_executesql @sql;

Dynamics SQL DOES bring issues into code, though, including SQL injection, not using query plans, and more. So, make sure you read up on dynamic sql and how to mitigate the issues it brings.

Charlieface
  • 52,284
  • 6
  • 19
  • 43