Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass variable to select statement as column name in SQL Server [duplicate]

Tags:

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

like image 894
Mina Gabriel Avatar asked Oct 15 '12 12:10

Mina Gabriel


People also ask

Can you use a variable for a column name in SQL?

Answers. You can't do that directly. You have to create a dynamic sql statement using a var and execute the statement.

How do you pass variables in a select statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do you assign a select statement value to a variable in SQL?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can we have duplicate columns in SQL?

You can just add the new column to the table as nullable, either with SQL Server Management Studio by right clicking on the Table and clicking "Design" or by using an ALTER TABLE statement like this ALTER TABLE TableName ADD NewColumnName DataType NULL .


1 Answers

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) 
like image 120
Steve Avatar answered Oct 04 '22 03:10

Steve