using subquery instead of the tablename

zhanjian picture zhanjian · May 9, 2011 · Viewed 9.5k times · Source
Table Meta:
-------------------------------------
type                  tab_name
new                   tab_news
sports                tab_sps

Table tab_news
------
id

Table tab_sps
-------------------
id
xx

Now I want to use

SELECT id 
  FROM (SELECT tab_name 
          FROM Meta 
         WHERE type = 'news');

But it does not work, any ideas?

Answer

OMG Ponies picture OMG Ponies · May 9, 2011

SQL does not support a variable/etc for the table name -- the only means of supporting what you ask is by using dynamic SQL:

FOR i IN (SELECT tab_name
            FROM META m
           WHERE m.type = ?) LOOP
  EXECUTE IMMEDIATE 'SELECT * FROM '|| i.tab_name ||'';
END LOOP;