0

Hi I am trying to use for loop for retrieving data in oracle pl/sql but I am getting an error can someone help me

SET SERVEROUTPUT ON
DECLARE

  fname employees.first_name%TYPE;
  empid employees.employee_id%TYPE;
  CURSOR emp_cursor IS
  SELECT employee_id,first_name from employees ORDER BY employee_id;

BEGIN

  open emp_cursor;  
  FOR empid IN emp_cursor loop

  DBMS_OUTPUT.PUT_LINE('employee id is ' ||empid || 'first name is '||fname);

end LOOP;

END;

I am getting an error on the DBMS output line something like the number or type of variables not right. I am trying to retrieve employee id and first name from employees table in oracle sample schema.

Can someone please guide me

2
  • u need not issue an OPEN statement.. As FOR LOOP do it implicitly for you! Commented Jan 27, 2014 at 8:46
  • What happened with the solution below? Please clarify why it was unaccepted! Commented May 5, 2018 at 17:33

1 Answer 1

2

USING FOR..LOOP in CURSORS.

SET SERVEROUTPUT ON
DECLARE
  /* DECLARE Cursor */
  CURSOR emp_cursor IS
  SELECT employee_id,first_name from employees ORDER BY employee_id;

BEGIN
  FOR empid IN emp_cursor loop
     /* empid already has the row details, you don't need to have any other variables */
     DBMS_OUTPUT.PUT_LINE('employee id is ' ||empid.employee_id || 'first name is '||empid.first_name);

  end LOOP;

END;
/

USING OPEN FETCH and CLOSE

SET SERVEROUTPUT ON
DECLARE

  fname employees.first_name%TYPE;
  empid employees.employee_id%TYPE;
  CURSOR emp_cursor IS
  SELECT employee_id,first_name from employees ORDER BY employee_id;

BEGIN

  open emp_cursor; 

  /* LOOP until the cursor is empty */
  LOOP 
      FETCH emp_cursor INTO empid,fname;
      /* Now we fetch data from cursor, and put it into our variables */
      EXIT WHEN emp_cursor%NOTFOUND;

      DBMS_OUTPUT.PUT_LINE('employee id is ' ||empid || 'first name is '||fname);
  END LOOP;

  /* As we OPEN'ed the cursor manually, we have to CLOSE it without fail */
  CLOSE emp_cursor;

END;
/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.