How to assign table name by a dynamic variable in the FROM expression

  • Hello All,

    I found that I can't use a dynamic variable in the FROM expression to assign the table name in T-SQL, are there any way to do so?

    Query:

    declar @Table_Name varchar(500)

    set @Table_Name='S_EVT_ACT'

    Select * from @Table_Name

    Error MSG:

    Msg 1087, Level 15, State 2, Line 3

    Must declare the table variable "@Table_Name".

  • Try running this query

    --------------------------------

    declare @Table_Name varchar(500)

    set @Table_Name='S_EVT_ACT'

    Declare @Query Varchar (500)

    set @Query='select * from ' + @Table_Name

    Exec (@Query)



    Pradeep Singh

  • I am sorry I think I didn't make myself clear. Here is another query.

    Query:

    declar @Table_Name varchar(500)

    declar @string char(500)

    set @Table_Name='S_EVT_ACT'

    Select @string=string from @Table_Name

    The problem is I don't want to use EXEC(@combined query string) to temperately save the results to a table or something and then fetch it again, how can I do?

  • The problem is I don't want to use EXEC(@combined query string) to temperately save the results to a table or something and then fetch it again, how can I do?

    We're storing the query in the variable @query.

    Exec is used to execute the query. Results do not gets stored to a table; instead records are returned to the user firing the query as if you were firing a normal SELECT statement. i dont see a difference in execution mechanism...



    Pradeep Singh

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

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