[sql-server-2008] Can I pass variable to select statement as column name in SQL Server

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

This question is related to sql-server-2008

The answer is


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)