Table Name as a variable?

  • I have the need to compare the data in two tables, to make the SP easier to run, I wanted the table names to be variables, is this possible?

    A simpler version of the query that I am trying to run is :

     

    Declare @name as Varchar(80)

    Set @name = 'QCP_HRA'

    Select top 10 *

    from @name

    When I run this, I get the following error message:

    Server: Msg 137, Level 15, State 2, Line 5

    Must declare the variable '@name'.

    I know that this is doable, I had to do it in a previous life, I just forgot how.

  • You need to use dynamic sql.

    Declare @name as Varchar(80), @SQL VARCHAR(8000)

    Set @name = 'QCP_HRA'

    SET @SQL = 'SELECT * FROM ' + @name

    EXEC (@SQL)

     

     

     

     

  • Thank you, I knew it was something like that but I could not remember excatly how to do it, this is a really powerful tool, thank you again, it works wonderfully!

     

     

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

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