简体   繁体   中英

How do I assign multiple variables based on other columns values from select (PL/SQL)

Hi I'm fairly new to this, wondering how to assign values to multiple variables from a select statement so that i can use them in apex.

DECLARE
emails_hr varchar2(2000);
emails_ops varchar2(2000);
emails_finance varchar2(2000);
emails_sales varchar2(2000);
BEGIN

SELECT
  DEPARTMENT,
  LISTAGG(lower(EMAIL), '; ') WITHIN GROUP (ORDER BY DISPLAY_AREA) as EMAILS
FROM (
  select
    DEPARTMENT,
    EMAIL 
from CONTACT_TABLE
    where EMAIL is not NULL
    and OFFICE_ID = 100
 )
GROUP BY DEPARTMENT;

END;

The select query returns this:

DEPARTMENT          EMAILS                  

human resources     abby@gmail.com                  
operations          bob@gmail.com; carol@gmail.com; dave@gmail.com  
finance             emma@gmail.com; fred@gmail.com          
sales               gary@gmail.com; harry@gmail.com; ian@gmail.com  

It's expecting an INTO clause so I tried putting the LISTAGG part in a case statement to select into the variables based on department, but I can't get it to a point where I don't just get a syntax error.

EDIT: I should mention, not all offices have all 4 departments

My head hurts, thanks in advance for any help

As mentioned in the comments it is hard to work out exactly what you want to do but I think you might be after a cursor.....

DECLARE
   emails_hr varchar2(2000);
   emails_ops varchar2(2000);
   emails_finance varchar2(2000);
   emails_sales varchar2(2000);

   CURSOR C_DEPARTMENTS IS       
   SELECT DEPARTMENT,
     LISTAGG(lower(EMAIL), '; ') WITHIN GROUP (ORDER BY DISPLAY_AREA) as EMAILS
   FROM (SELECT DEPARTMENT, EMAIL 
         FROM  CONTACT_TABLE
         WHERE EMAIL is not NULL
         AND   OFFICE_ID = 100
   )
  GROUP BY DEPARTMENT;

BEGIN
  FOR v_row in c_departments LOOP
    -- do whatever you want in here eg
    dbms_output.put_line('department = ' || v_row.department);
    dbms_output.put_line('emails = ' || v_row.emails);
  END LOOP;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM