简体   繁体   中英

SQL dynamically join to a user/data supplied table

I want something like:

SELECT * from metric_data m, 
    (SELECT table_for_join FROM join_tables WHERE from_table = 'usersupplied') u,
    WHERE m.id = u.id

Is this possble?

I'm using oracle 11g if that matters.

I think you need to use dynamic sql. Something like this (sorry, I'm not able to test it at the moment, but I hope it should work

CREATE PROCEDURE getMetricData (in_table_name varchar2)
IS 
  real_tab_name varchar(32);
BEGIN
  SELECT table_for_join into real_tab_name 
  FROM join_tables WHERE from_table = in_table_name;
  IF (real_tab_name IS NOT NULL) THEN
  EXECUTE IMMEDIATE 'SELECT * from metric_data m, ' || real_tab_name || ' u 
   WHERE m.id = u.id';
  END IF;
END;
SELECT m.* from metric_data m
LEFT JOIN join_tables u
ON(m.id = u.id AND u.from_table='usersuplied')
WHERE 1=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM