user3766910
user3766910

Reputation: 55

Can I pass variable to select statement as column name with where condition value from 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 with condition where value from variable

I'm using SQL Server 2008 (9.0 RTM)

This will be a stored procedure

Thanks in advance

Upvotes: 1

Views: 1523

Answers (1)

Avitus
Avitus

Reputation: 15958

You can do this using dynamic sql but this is BAD practice.

Here's the answer to your problem but I most certainly wouldn't do this because it opens you up to sql injection attacks.

create procedure GetColumn
     @columnName varchar(50), 
     @g varchar(200)
as
   declare @str varchar(2000)
   set @str = 'select [' + @columnName + '] from dbo.tblBatchDetail where Gnumber = ' + @g

   exec ( @str ) 

GO

Upvotes: 1

Related Questions