I\'ve got the following problem. My table (geo_table
) structure is as follows:
foreign_table_id | foreign_table_name | some_other_fields...
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
This should be done dynamically :
declare @tablename varchar(50)
set @tablename = 'test'
declare @sql varchar(500)
set @sql = 'select * from ' + @tablename
exec @sql