title: How to declare a cursor after BEGIN?
body: <p>I want to know if a cursor can be declared after <code>BEGIN</code>.</p>
  
  <p>And how can I export the result of the plsql to an Excel sheet, because I have to run this procedure as a job.</p>
  
  <pre><code>CREATE OR REPLACE PROCEDURE masc(v_amsprogramid VARCHAR2) AS
  
    v_mid VARCHAR2(50);
    v_sid VARCHAR2(50);
  
    CURSOR c1 IS
      SELECT DISTINCT mid
      FROM table_a WHERE aid = v_aid
      ORDER BY mid;
  
    BEGIN
  
      OPEN c1;
  
      LOOP
        FETCH c1 INTO v_mid;
        EXIT WHEN c1%NOTFOUND;
  
        DECLARE
          CURSOR c2 IS
            SELECT DISTINCT sid INTO v_sid
            FROM table_b WHERE mid = v_mid;
  
        BEGIN
          OPEN c2;
          LOOP
  
            FETCH c1 INTO v_mid;
            EXIT WHEN c1%NOTFOUND;
  
            dbms_output.PUT_LINE('MID : ' || v_mid);
            dbms_output.PUT_LINE('Sid : ' || v_sid);
  
          END LOOP;
  
          CLOSE c2;
        END LOOP;
  
        CLOSE c1;
    END masc;
  </code></pre>