创建动态 oracle sql 查询

Creating dynamic oracle sql query

我需要在 Oracle 的 PLSQL 中动态创建查询。

我的意思是这样的:

declare 
secondPart varchar2(100);


begin
select COLUMN into secondPart from TABLE where columnName='someName';
update firstPart_secondPart set SOME_COLUMN=1;
end

所以基本上我想做的是将一些常量字符串 (firstPart_) 与动态值组合起来

您可以按如下方式使用execute immediate

declare 
secondPart varchar2(100);
begin
select COLUMN into secondPart from TABLE where columnName='someName';
execute immediate 'update firstPart_' ||secondPart || ' set SOME_COLUMN=1';
--commit/rollback;
end;
/

例如:

SQL> create table test as
  2    select 'empno' column_name, 'p' second_part from dual union all
  3    select 'deptno'           , 'pt'            from dual;

Table created.

SQL> set serveroutput on
SQL> declare
  2    first_part varchar2(20) := 'em';
  3    l_str varchar2(200);
  4  begin
  5    select 'update ' || first_part || t.second_part ||
  6           '  set comm = -100 where comm is null'
  7    into l_str
  8    from test t
  9    where t.column_name = 'empno';
 10
 11    dbms_output.put_line(l_str);
 12    execute immediate l_str;
 13  end;
 14  /
update emp  set comm = -100 where comm is null

PL/SQL procedure successfully completed.

结果:

SQL> select empno, ename, comm from emp;

     EMPNO ENAME            COMM
---------- ---------- ----------
      7369 SMITH            -100
      7499 ALLEN             300
      7521 WARD              500
      7566 JONES            -100
      7654 MARTIN           1400
      7698 BLAKE            -100
      7782 CLARK            -100
      7788 SCOTT            -100
      7839 KING             -100
      7844 TURNER              0
      7876 ADAMS            -100
      7900 JAMES            -100
      7902 FORD             -100
      7934 MILLER           -100

14 rows selected.

SQL>