Search code examples
sqlvariablesdeclare

sql issue with declare query


I've got a java application that I'm using to retrieve information from a table in sql.
The problem is that the tables change depending on the main application that is using them; there is a view that has all of the active information from the active table eg table_all which is fine, what i want to do is search for a particular number in table that was a part of the view

DECLARE @iss int, @act_tb char(1)
SET @iss = (select cust_nr from table_all where num = '123456789')
SET @act_tb = (select curr_table_active from pc_group where cust_nr = @iss)
select * from pc_grp_@iss_@act_tb 

so what i would now want to do is update a field in pc_grp_@iss_@act_tbenter code here format is pc_grp_<@iss>_<@act_tb>.

is there any way i can do that as pc_grp_@iss_@act_tb is picked up as a table and not a variable table name. Many thanks


Solution

  • i think you are looking for this-:

    Declare @query as varchar(Max);
    Set @query='Select * from select * from pc_grp_'+Cast(@iss as varchar)+'_'+Cast(@act_tb as varchar) ;
    Exec(@query)