【问题标题】:PL/SQL Using SELECT inside of CONDITIONPL/SQL 在 CONDITION 内使用 SELECT
【发布时间】:2021-10-29 02:18:03
【问题描述】:

我在docker 容器中安装了Oracle 实例,并在容器启动时放置了sql 脚本:

Dockerfile:

FROM...
...
CMD powershell echo @C:\scripts\entrypoint.sql | sqlplus -S sys/password as sysdba

entrypoint.sql:

set serveroutput on format wrapped;
declare
userexist integer;
db_schema_version varchar2(20);
begin
  select count(*) into userexist from dba_users where username='DEV';
  if (userexist = 0) then
    dbms_output.put_line('SCHEMA NOT FOUND!');
    dbms_output.put_line('CONNECTION STRING: ' || 'sqlplus sys/password@localhost/ORA193 as sysdba');
  elsif (userexist = 1) then
    dbms_output.put_line('SCHEMA FOUND!');
    select DB_SCHEMA_VERSION into db_schema_version from DEV.VER_INFO where CODE = 'CORE';
    dbms_output.put_line('DB_SCHEMA_VERSION: ' || db_schema_version);
    dbms_output.put_line('CONNECTION STRING: ' || 'sqlplus DEV/password@localhost/ORA193');
  end if;
end;
/

问题是查询 select DB_SCHEMA_VERSION into db_schema_version from DEV.VER_INFO where CODE = 'CORE'; 正在执行,即使 elsif 条件是 false

编写PL/SQL 以获取select 查询仅在条件为true 的情况下执行的正确方法是什么?

【问题讨论】:

  • @WalterMitty 这是 PL/SQL,所以then 语句的范围在下一个end if 结束,并且没有脚本解释器。

标签: windows oracle docker powershell plsql


【解决方案1】:

问题不在于条件为假时正在执行查询。问题是必须先编译 PL/SQL 块才能执行它。如果它引用了不存在的对象,则编译失败(如果您发布错误消息,很明显这是编译错误而不是运行时错误)。

如果要引用可能不存在的对象,则需要使用动态 SQL。类似的东西

execute immediate 'select db_schema_version from dev.ver_info'
             into db_schema_version;

在这种情况下可以工作。在更复杂的情况下,您可能希望在本地变量中构建 SQL 语句,您可以记录该变量以进行调试或可能使用 dbms_sql 包。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2012-06-27
    • 1970-01-01
    • 2017-03-18
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多