29

Possible Duplicate:
SQL: Select dynamic column name based on variable

I have the following simple select statement:

 DECLARE @value varchar(10) 
 SET @value = 'intStep' 

 SELECT @value FROM dbo.tblBatchDetail 

I have tried

 SELECT CAST(@value AS varchar(10)) FROM dbo.tblBatchDetail 

and all I get a list of intstep

QUESTION: can I pass variable as column name to this statement? Or what is the best way of doing this

I'm using SQL Server 2008 (9.0 RTM)

This will be a stored procedure

Thanks in advance

Community
  • 1
  • 1
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • 1
    I think this is a dup of this question [Using dynamic SQL to specify a column name by adding a variable to simple sql query](http://stackoverflow.com/questions/7123659/using-dynamic-sql-to-specify-a-column-name-by-adding-a-variable-to-simple-sql-qu) – Spevy Oct 15 '12 at 13:01

1 Answers1

53

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Steve
  • 213,761
  • 22
  • 232
  • 286