根据存储在字段中的查询运行SQL?

时间:2012-04-10 09:46:09

标签: sql oracle plsql

我正在尝试使用存储在另一个表中的查询来填充具有特定值的数据库。

表1:

ID      SQL                                         Title
1       select ID from userTable where ID = 1       Query 1
2       select ID from userTable where ID > 7       Query 2

我基本上需要获取'SQL'字段,并使用上面的信息填充另一个表,一旦脚本运行它将看起来像:

ID      userID      Title
1       1           Query 1
2       8           Query 2
2       9           Query 2
2       10          Query 2

等等。

我希望这是有道理的,我绝对不知道是否有可能 - 我已经尝试将其创建为一个过程,但无论如何我都无法在程序中运行表1中的'SQL'代码。< / p>

或者我会用PHP来做,虽然最好把它变成SQL,因为它更容易自动化。

谢谢

1 个答案:

答案 0 :(得分:3)

这是一件奇怪的事情(我会查询原因)但是这段代码应该这样做:

declare
  rc sys_refcursor;
  l_id table1.id%type;
begin
  for r_sql in (select id, sql, title from table1) loop
    open rc for r_sql.sql;
    loop
      fetch rc into l_id;
      exit when rc%notfound;
      insert into table2 (id, userid, title) values (r_sql.id, l_id, r_sql.title);
    end loop;
    close rc;
  end loop;
end;