Tuesday, February 14, 2012

column as variable

I have a problem that I'm sure is very simple to answer for anyone that knows a bit of T-SQL. In a stored procedure, I simply want to concatenate a string variable containing a column name into a Select statement.

For example:
I want to execute the following statement but using a variable for the column name:

Select * from tblmet1araw where JulianDay = 1

JulianDay is an integer
This is how I have my code set up:

declare @.xxx as varchar(20)
set @.theday = 'JulianDay'

select * from tblmet1araw where @.theday = 1

I get the following error:
Server: Msg 245, Level 16, State 1, Line 4
Syntax error converting the varchar value 'JulianDay' to a column of data type int.declare @.col varchar(10)
set @.col='id'
exec('select * from sysobjects where '+@.col+'=1')|||Thanks. That works.

No comments:

Post a Comment