Table name as parameter of the function

  • Hello,

    I am trying to make a query like this :

    SELECT field

    FROM @tablename <---||
    WHERE ...

    In any way I have an error

    [@tablename]
    '@tablename'
    "@tablename"

    Sql server does not recognize the object name.

    Thank you
    Bye Pier

  • The object of the FROM clause may not be a variable.  You'll need to use dynamic SQL to do this.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • declare @TableName as varchar(100)

    declare @cmd as varchar(8000)

    set @cmd = 'select * from ' + @TableName + ' where ...'

    exec (@cmd)

    thank you

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply