相当于 foreach 循环的 Oracle PL

标签 oracle loops plsql

我需要遍历大约 10 个字符串,这些都是我事先知道的——我不需要从任何地方SELECT它们。

我尝试过:

BEGIN
    FOR tab IN ('one', 'two', 'three')
    LOOP
        EXECUTE IMMEDIATE 'DROP TABLE ' || tab;
    END LOOP;
END;

但这不起作用(LOOP 是意外的)...

有办法吗?

最佳答案

declare
   type t_strings is table of varchar2(100);
   strings t_strings:=t_strings('one','two','three');
begin
   for i in 1..strings.count loop
      dbms_output.put_line(strings(i));
   end loop;
end;
/

结果:

one
two
three

或者您可以使用自己的快捷函数: http://orasql.org/2017/10/02/plsql-functions-iterate-and-keys-for-associative-arrays/

顺便说一句,Oracle 21 有一些 FOR-LOOP 的新特性:

所以可以改写为:

declare
   type t_strings is table of varchar2(100);
begin
   for str in values of t_strings('one','two','three') loop
      dbms_output.put_line(str);
   end loop;
end;
/

关于相当于 foreach 循环的 Oracle PL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67377584/

相关文章:

javascript - 将 blob 从 JS 保存到 Oracle SQL?

oracle - 如何使用 "impdp"命令导入带端口号的 .dmp 数据?

sql - 除以表中的几个元素

python - 卡在 Python 3 中的错误(异常、循环)

bash - 超时重试 Bash 命令

javascript - 在对象中按名称查找嵌套属性的最佳方法

oracle - PL/SQL 函数在循环后停止运行

c++ - 如何使用 oci 或任何其他库以 sys 帐户登录 oracle

sql - 在oracle sql中加入sql View

Oracle PL/SQL : Conditional Where Clause