fetch table name from a column for from clause

僤鯓⒐⒋嵵緔 提交于 2019-11-28 06:54:14

问题


I have a view t with me which has a column for table name and another column which has where clause condition.

    id| name|table_in| where_clause

    1 | Sam | t1 | age = 22

    2 | John| t2 | age = 23 and sex = 'male'

and so on...

Now, I have put the records in a cursor and I want to run each query.

    create or replace procedure create_cursor 
    is

    CURSOR v_records is
    select * from t ;

    begin

    FOR temp IN v_records LOOP
        INSERT INTO myTable (id, name)
        select temp.id, temp.name 
        from temp.table where temp.where_clause;

        END LOOP;


    end;
    /

myTable is another table in which I want to put the records for next purpose.


回答1:


@Akshay,

Please find the code below for your reference.

Create or replace procedure create_cursor is
l_statement varchar2(32767);
cursor v_records is
  select * from t;
begin
for temp in v_records
loop
  l_statement := 'INSERT INTO myTable (id, name) select '||temp.id||','
   ||temp.name|| ' from ' || temp.table1 
   || ' where ' || temp.where_clause;

  execute immediate l_statement;
  end loop;
end;
/



回答2:


You need dynamic sql to do this:

CREATE OR REPLACE PROCEDURE create_cursor
IS
  l_statement VARCHAR2(32767);
  CURSOR v_records
  IS
    SELECT * FROM t;
BEGIN
  FOR temp IN v_records
  LOOP
    l_statement := 'INSERT INTO myTable (id, name)
          select id, name from ' || temp.table || 
          ' where ' || temp.where_clause;
    EXECUTE immediate l_statement;
  END LOOP;
END;
/


来源:https://stackoverflow.com/questions/41541100/fetch-table-name-from-a-column-for-from-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!