问题
There is a table that contains a column containing a SQL select expression. See the following example:
╔════╦════════╦═══════════════════════════════════════════╗
║ ID ║ Code ║ Expression ║
║ 1 ║ B12321 ║ SELECT * FROM table WHERE code LIKE '%' ║
║ 2 ║ A35525 ║ SELECT * FROM table WHERE code = '1234' ║
║ 3 ║ C23213 ║ SELECT * FROM table WHERE code <> '%D' ║
╚════╩════════╩═══════════════════════════════════════════╝
I want to loop throught the Expression column, execute those statements and insert the result into another table. Is this even possible? I can't find related questions about that. Besides that, I read about a using a cursor to loop throught the table but there is a lot of negativity about that.
If possible, can you provide usefull links about the question I have, or even better a sample code doing this.
回答1:
Yes, possible by using dynamic SQL in which qualify excerpt code
with colon as :code
, and use double loop as below :
SQL> desc tab2
Name Type
---------- -------------
ID VARCHAR2(20)
NAME VARCHAR2(100)
SQL> create table tab3( ID varchar2(20), name varchar2(50));
SQL> declare
v_row tab2%rowtype;
v_cursor sys_refcursor;
begin
for c in ( select ID, code, expression from tab1 )
loop
open v_cursor for replace(c.expression,' code ',' :code ') using c.code;
loop
fetch v_cursor
into v_row;
exit when v_cursor%notfound;
insert into tab3 values( v_row.id,v_row.name );
end loop;
close v_cursor;
end loop;
end;
/
where tab2
is the common table
within the expression
column.
回答2:
You want dynamic SQL. As you don't want to return any data, this is possible with a small PL/SQL procedure:
create or replace procedure insert_by_code(in_code varchar2) as
begin
for rec in (select expression from mytable where code = in_code) loop
execute immediate 'insert into other_table ' || rec.expression;
commit;
end loop;
end insert_by_code;
or ad hoc with an anonymous block:
begin
for rec in (select expression from mytable where code = :code) loop
execute immediate 'insert into other_table ' || rec.expression;
commit;
end loop;
end;
来源:https://stackoverflow.com/questions/59078119/how-to-use-column-value-as-select-expression