user977645
user977645

Reputation: 1167

SQL - Can I pass a variable to be used in the FROM statement?

Can I pass a variable to a SELECT statement?

I keep getting an error message saying I need to declare it.

However, it is declared.

SELECT (list of columns)
FROM @database_table

Upvotes: 1

Views: 112

Answers (3)

ganders
ganders

Reputation: 7441

Yes, use dynamic sql statements to build your select statement.

-- Procedure input parameters
@TableName varchar(50)

-- Query guts
Declare @sql varchar(2000)
Set @sql = 'Select columnname from ' + @TableName
exec (@sql)

Upvotes: 0

Taryn
Taryn

Reputation: 247810

You are looking to use Dynamic SQL to perform this type of query.

The Curse and Blessings of Dynamic SQL

Here is a quick sample

declare @sqlstatement nvarchar(4000)
declare @table sysname
set @table = 'yourTableName'

set @sqlstatement = 'SELECT * FROM ' + QUOTENAME(@table)
exec(@sqlstatement)

Upvotes: 7

Gordon Linoff
Gordon Linoff

Reputation: 1270351

The one time you can do what you want is when you use table variables. You have to define the variables as:

declare @name table (<column list>)

This is alternative method of declaring a temporary table.

Other than this, I fully agree with bluefeet. You should read the link he posted.

Upvotes: 0

Related Questions