Variable in From Statement?

  • Is there a way to use a variable for the table name in a from statement?  I'm using a cursor to loop through and run the same query on a bunch of tables but whenever I try to use a var for the table name it tells me I need to declare the variable

    Test Example:

    Declare   @Tbl_Name varchar(20)

    Set @Tbl_Name = 'My_Table'

    Select * From @Tbl Name (This gives me an error that I need to declare the variable @Tbl_Name)

    Yet Print @Tbl_Name is OK...

    TIA, Erin

  • I know that using exec, you can have a variable name in the from clause.

    exec('Select * From '+ @Tbl Name)

    Hoping this helps...

  • You can use dynamic sql:

     

    Declare   @Tbl_Name varchar(200)

    Declare   @SQL varchar(200)

    Set @Tbl_Name = 'YourTable'

    set @SQL = 'Select * From '+@Tbl_Name

    exec(@SQL)

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

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