PL / SQL:如何从表中选择数据并输入到包接受数组类型?

时间:2013-05-08 15:06:37

标签: database oracle plsql

我有一个PL / SQL电子邮件包,如下所示:

create or replace package mail_pkg 
as
PRAGMA SERIALLY_REUSABLE; -- this avoids ORA-04068 error
type array is table of varchar2(255);

procedure send( p_sender_email in varchar2,
            p_from         in varchar2 default null,
            p_to           in array default array(),
            p_cc           in array default array(),
            p_bcc          in array default array(),
            p_subject      in varchar2 default null,
            p_body         in clob default null);

示例用法是:

 begin
    mail_pkg.send( p_sender_email => 'tim@company1.com',
               p_from => 'John Smith <johns@company2.com>',
               p_to => mail_pkg.array( 'greg@company3.com','sarah@company4.com'),
               p_cc => mail_pkg.array( 'admin@company5.com' ), 
               p_bcc => mail_pkg.array( 'sue@company5.com' ), 
               p_subject => 'This is my subject', 
               p_body => 'Hello, this is the mail you requested.' );
    end;

[注意:对于任何寻找电子邮件包的人来说,这是我从中得到的链接: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:255615160805]

我想用它来发送电子邮件,但必须动态输入p_to输入中的电子邮件地址。也就是说,我不能像上面那样对它们进行硬编码。它们需要来自SELECT语句。我熟悉编写select语句,但我不知道如何将selecte语句的结果转换为我可以包含在

中的格式
p_to => mail_pkg.array( WHAT GOES HERE??? ),

代码。

任何人都知道如何连接SELECT语句(返回一些电子邮件地址)以使用此程序包?

更新:

根据以下反馈,解决方案是:

create or replace procedure send_email ( 
  in_name IN varchar2
 )

AS

v_body clob;  
v_to_array mail_pkg.array := mail_pkg.array();
v_counter int := 1;

BEGIN

FOR r IN (SELECT person_email FROM email_table WHERE company_name=in_name) LOOP
  v_to_array.extend;
  v_to_array(v_counter) := r.person_email;
  v_counter := v_counter +1;
END LOOP;

-- send email

mail_pkg.send( p_sender_email => 'sam@company2.com',
               p_from => 'admin@company2.com',
               p_to => v_to_array,
               p_bcc => mail_pkg.array( 'tim@company3.com' ), 
               p_subject => 'the subject line goes here', 
               p_body => 'This is the body message.' );  

END send_email;

1 个答案:

答案 0 :(得分:3)

你可以分两步完成。第一步是在循环中使用SELECT语句并填充数组;第二步是在调用mail_pkg.send时使用该数组,可能是这样的:

declare
  v_counter number := 1;
  v_to_arr mail_pkg.array := mail_pkg.array();
begin
  for r in Select email_address from table_of_email_addresses loop
    v_to_arr.extend;
    v_to_arr(v_counter) := r.email_address;
    v_counter := v_counter +1;
  end loop;

  mail_pkg.send(p_to => v_to_arr, ... );
  --note: this code may require some fine-tuning.
  ...
end ;

正如评论中所建议的那样,这里可能会使用批量收集,可能就像这样简单:

declare
  v_to_arr mail_pkg.array := mail_pkg.array();
begin

  Select email_address
  bulk collect into v_to_arr
  from table_of_email_addresses;

  mail_pkg.send(p_to => v_to_arr, ... );
  --note: this code may require some fine-tuning.
  ...
end ;

我对批量操作有点生疏,你可能想自己阅读它们。