Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2006
    Location
    Leeds, UK
    Posts
    104

    Unanswered: using variables to select column names

    Hi

    I've tried declaring and setting variables in my sql statement and then trying to use them instead of defining a column directly - sorry quite hard to explain, i'll do a simple example

    eg

    DECLARE @column
    DECLARE @value
    SET @column = 'col1'
    SET @value = 'bloggs'

    Select * FROM table1 WHERE @column = @value

    It keeps returning no results even though i've tried

    Select * FROM table1 WHERE col1 = 'bloggs' -- which returns results

    I realise its the column which is not being selected, but there must be a way by using a variable?

    thanks

  2. #2
    Join Date
    Jun 2003
    Location
    Ohio
    Posts
    12,592
    Provided Answers: 1
    You cannot refer to database objects as variables. You will have to construct a dynamic SQL string from your variables and then run it using the EXEC command.
    ...and nine times out of ten this is a bad idea.
    If it's not practically useful, then it's practically useless.

    blindman
    www.chess.com: "sqlblindman"
    www.LobsterShot.blogspot.com

  3. #3
    Join Date
    May 2004
    Location
    Seattle
    Posts
    1,313
    Indeed.

    Please read and understand this before considering using dynamic sql:

    http://www.sommarskog.se/dynamic_sql.html

Posting Permissions

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