Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1

    Unanswered: Pass NVARCHAR (or other string-type) var as a column or table name in SQL

    Hey folks, the question is fairly simple, unfortunately the answer has proven rather elusive.

    Is it possible to declare a variable which would then be used to identify either a column or table in an SQL statement?

    Here's a basic idea of what I'd like to do:

    DECLARE @myVar AS NVARCHAR(50)

    SELECT *
    FROM @myVar

    or

    DECLARE @myVar AS NVARCHAR(50)

    SELECT @myVar
    FROM MyTable



    I'm probably looking for some sort of built in function that will accept an argument here... like COLUMN(@myVar) or something of the like. I just don't know where to look...
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    You'd have to use dynamic SQL, something like:
    Code:
    DECLARE @myVar AS NVARCHAR(50)
    
    EXECUTE ('SELECT * FROM ' + @myVar)
    -- or
    EXECUTE ('SELECT ' + @myVar + ' FROM MyTable')
    -PatP

Posting Permissions

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