如何使用列值作为选择表达式

问题描述 投票:0回答:3

[有一个表,其中包含一个包含SQL选择表达式的列。请参见以下示例:

╔════╦════════╦═══════════════════════════════════════════╗
║ 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'    ║
╚════╩════════╩═══════════════════════════════════════════╝

我想遍历Expression列,执行这些语句并将结果插入到另一个表中。这有可能吗?我找不到与此相关的问题。除此之外,我还读到了一个使用游标在表中循环的方法,但是关于它有很多消极的地方。

[如果可能,您能否提供有关我所遇到问题的有用链接,或者甚至可以提供一个示例代码来完成此操作。

sql oracle plsql expression
3个回答
0
投票

从Oracle文档中看一下本文档...有一个示例说明了您想要的内容。

https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/dynamic.htm#LNPLS629

希望有帮助!


0
投票

是的,可以通过使用动态SQL来实现,其中将摘录code的冒号限定为:code,并使用如下所示的双循环:

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;   
/

其中tab2table列中的通用expression


0
投票

您需要动态SQL。由于您不希望返回任何数据,因此可以通过一个小的PL / SQL过程来实现:

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;

或带有匿名阻止的临时对象:

begin
  for rec in (select expression from mytable where code = :code) loop
    execute immediate 'insert into other_table ' || rec.expression;
    commit;
  end loop;
end;
© www.soinside.com 2019 - 2024. All rights reserved.