开发者

Select using dynamically generated tablename

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

foreign_table_id | foreign_table_name | some_other_fie开发者_开发问答lds...

foreign_table_name stores names of different tables and foreign_table_id stores ids within these tables. What I want to do is check whether a row in the above mentioned table stores valid reference to some other table. Thus I need to select a row from foreign table which name is based on string stored in foreign_table_name. My code didn't work because it has syntax error but it clearly presents what I wanted to achieve:

SELECT foreign_table_id, foreign_table_name FROM `geo_table` gt
WHERE (
    SELECT COUNT(*) FROM gt.foreign_table_name AS t
    WHERE gt.foreign_table_id = t.uid
) > 0


This should be done dynamically :

declare @tablename varchar(50)
set @tablename = 'test'
declare @sql varchar(500)
set @sql = 'select * from ' + @tablename
exec @sql 


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜