暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 在同一过程中创建和插入表

askTom 2017-03-10
181

问题描述

我在一个过程中有一个过程,我必须创建一个表并插入到该表中,插入值来自关联数组,
如何通过使用动态sql来执行此操作。请建议我。提前感谢 :)

专家解答

如果值列表很小,则可以轻松地在数组周围循环并一次插入值行,例如

SQL> declare
  2    type numlist is table of number index by pls_integer;
  3    n numlist;
  4  begin
  5    execute immediate 'create table t ( x int )';
  6    for i in 1 .. 10 loop
  7       n(i) := i;
  8    end loop;
  9
 10    for i in 1 .. n.count loop
 11      execute immediate 'insert into t values (:val)' using n(i);
 12    end loop;
 13  end;
 14  /

PL/SQL procedure successfully completed.

SQL>
SQL> select * from t;

         X
----------
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10

10 rows selected.
复制


但是,如果数组很大,您可能希望使用PLSQL动态编写一些PLSQL。在这种情况下,我们可能需要提前知道类型定义,例如

SQL> drop table t purge;

Table dropped.

SQL>
SQL> create or replace
  2  package pkg is
  3    type numlist is table of number index by pls_integer;
  4  end;
  5  /

Package created.

SQL>
SQL>
SQL> declare
  2    n pkg.numlist;
  3  begin
  4    execute immediate 'create table t ( x int )';
  5    for i in 1 .. 10 loop
  6       n(i) := i;
  7    end loop;
  8
  9    execute immediate
 10    'declare
 11       x pkg.numlist := :val;
 12     begin
 13       forall i in 1 .. x.count
 14         insert into t values (x(i));
 15     end;
 16    ' using n;
 17  end;
 18  /

PL/SQL procedure successfully completed.

复制


「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论