Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2004
    Posts
    31

    Unanswered: 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.

  2. #2
    Join Date
    Jul 2002
    Location
    Village, MD
    Posts
    621
    declare @col varchar(10)
    set @col='id'
    exec('select * from sysobjects where '+@col+'=1')

  3. #3
    Join Date
    Jun 2004
    Posts
    31
    Thanks. That works.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •