Select using dynamically generated tablename

前端 未结 2 1605
说谎
说谎 2021-01-15 22:01

I\'ve got the following problem. My table (geo_table) structure is as follows:

foreign_table_id | foreign_table_name | some_other_fields...


        
相关标签:
2条回答
  • 2021-01-15 22:36

    If you know all possible table names then you can implement it using conditional syntax:

    SELECT foreign_table_id, foreign_table_name FROM `geo_table` gt
    WHERE 
        CASE gt.foreign_table_name
            WHEN 'table1' THEN 
                EXISTS (
                    SELECT * FROM table1
                    WHERE id = gt.foreign_table_id
                )
            WHEN 'table2' THEN 
                EXISTS (
                    SELECT * FROM table2
                    WHERE id = gt.foreign_table_id
                )
            ELSE
                FALSE
        END
    
    0 讨论(0)
  • 2021-01-15 22:47

    This should be done dynamically :

    declare @tablename varchar(50)
    set @tablename = 'test'
    declare @sql varchar(500)
    set @sql = 'select * from ' + @tablename
    exec @sql 
    
    0 讨论(0)
提交回复
热议问题