【问题标题】:Conditionally calling sql scripts in sql plussql plus中条件调用sql脚本
【发布时间】:2020-09-22 07:31:33
【问题描述】:

我有两个脚本需要根据我的数据库中是否存在表来执行。

所以我创建了如下第三个脚本,它检查条件并调用相应的脚本。 [因为我的安装程序无法访问db,并且安装时只能调用一个脚本]

declare
  cnt number;
begin
  select count(*) 
  into cnt
  from all_tables where table_name = 'VQ_REPORT_LAUNCHER';


if (cnt>0) then
  begin
    @VQ_Alter_Script.sql;
  end;
else
  begin
    @VQ_Create_Script.sql;
  end;
end if;

结束;

我收到以下错误 - 第 10 行的错误: ORA-06550:第 10 行,第 1 列: PLS-00103:在预期以下之一时遇到符号“CREATE”:

注意 - 当我直接从 sql plus 执行我的创建/更改脚本时,它可以工作。 只有当我尝试使用 IF-ELSE 通过第三个脚本执行它们时,我才会在 sql plus 中收到上述错误。

【问题讨论】:

  • 如果不使用不同的近似值,您无法从 PL/SQL 调用 sql 脚本,例如 SQL_SCRIPT 作业类型的 DBMS_SCHEDULER 外部 API
  • 脚本将从安装程序调用,我们只需要检查表是否存在并相应地调用另一个脚本。不能在 .sql 中完成吗?

标签: sql oracle cmd sqlplus


【解决方案1】:

您可以使用替换变量来决定运行哪个脚本。

column script_name new_value script_name

select case count(*)
         when 0 then 'VQ_Create_Script.sql'
         else 'VQ_Alter_Script.sql'
       end as script_name
from all_tables
where table_name = 'VQ_REPORT_LAUNCHER';

@&script_name

或者如果只有部分名称更改,您可以这样做:

column script_type new_value script_type

select case count(*) when 0 then 'Create' else 'Alter' end as script_type
from all_tables
where table_name = 'VQ_REPORT_LAUNCHER';

@VQ_&script_type._Script.sql

您可以根据需要在查询部分周围添加set termout offset termout on 等设置以将其隐藏,并使用set verify 决定是否显示正在发生的替换。

根据您以哪个用户身份运行它,您可能需要检查 user_tables 而不是 all_tables,或者将预期的表所有者作为过滤器的一部分,这样您就不会意外选择表在错误的架构中具有相同的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 2012-11-13
    • 2019-06-06
    • 1970-01-01
    • 2012-05-11
    • 2011-01-30
    • 2016-04-12
    • 2019-02-25
    相关资源
    最近更新 更多