Search code examples
sqloracle-databaseplsqlsubqueryrownum

subquery for getting top 3 rownum not work in pl/sql


DECLARE
    CURSOR EMPCUR 
      SELECT EMPNO,ENAME,SAL,ROWNUM 
        FROM (SELECT * 
                FROM EMP 
               ORDER BY SAL DESC) 
       WHERE ROWNUM<=3 
       ORDER BY ROWNUM;
BEGIN
  FOR EMPREC IN EMPCUR
  LOOP
    DBMS_OUTPUT.PUT_LINE('RANK '||EMPREC.ROWNUM);
    DBMS_OUTPUT.PUT_LINE(EMPREC.EMONO||' - '||EMPREC.ENAME||' - '||EMPREC.SAL);
  END LOOP;
END;
/

This code does not work:

ERROR at line 2: ORA-06550: line 2, column 17: PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( ; is return The symbol "is" was substituted for "SELECT" to continue.


Solution

  • You have missed a IS on cursor declaration and there is a typo in line7 EMPREC.EMONO.

    Try like this,

    DECLARE
        CURSOR EMPCUR IS  SELECT EMPNO,ENAME,SAL,ROWNUM FROM (SELECT * FROM EMP ORDER BY SAL DESC) WHERE ROWNUM<=3 ORDER BY ROWNUM;
    BEGIN
        FOR EMPREC IN EMPCUR
        LOOP
            DBMS_OUTPUT.PUT_LINE('RANK '||EMPREC.ROWNUM);
            DBMS_OUTPUT.PUT_LINE(EMPREC.EMPNO||' - '||EMPREC.ENAME||' - '||EMPREC.SAL);
        END LOOP;
    END;
    /