SQL query dynamic table name in FOR

前端 未结 3 1458
耶瑟儿~
耶瑟儿~ 2020-12-19 07:11

I have a table tbl1 which has a column tbl_names. This column contains the name of some other tables.
Now I want to write a query in th

相关标签:
3条回答
  • 2020-12-19 07:14

    You can use prepared statements

    SET @a = (select tbl_names from tbl1);
    SET @x := CONCAT('SELECT * FROM ', @a);
    Prepare stmt FROM @x;
    Execute stmt;
    DEALLOCATE PREPARE stmt;
    

    PREPARE Syntax

    Cheers.

    0 讨论(0)
  • 2020-12-19 07:15

    You'll need to use some dynamic SQL. Build up a SQL string with the query that you want to execute and then call exec(@sql)

    Full example:

    declare cur cursor for
    select tbl_names from tbl1
    
    declare @sql varchar(100), @tbl varchar(100)
    
    open cur
    
    fetch cur into @tbl
    
    while @@FETCH_STATUS = 0 begin
        set @sql = 'select * from ' + @tbl
        exec(@sql)
        fetch cur into @tbl
    end
    
    close cur
    deallocate cur
    
    0 讨论(0)
  • 2020-12-19 07:25

    Just add a pseudonim to the subquery:

    select * from (select tbl_names from tbl1) a;
    

    Good luck )

    0 讨论(0)
提交回复
热议问题