I just started with PL/SQL, so, please be kind. I have a simple problem, I want to extract distinct names from a table. When I do that, inside the loop, I am going to do on each of those distinct names some other operations.
I am stuck on how to get the unique names inside a loop. What I do is not working because if I have:
1 MARY
2 MARY
3 JOHN
I am outputting:
MARY
MARY
Instead of:
MARY
JOHN
This is my code:
create or replace PROCEDURE CREATE_TABLE
(
NM OUT VARCHAR2,
tot OUT NUMBER
)
AS
BEGIN
SELECT count(DISTINCT NAME) INTO tot FROM MYTABLE;
FOR r IN 1..tot
LOOP
SELECT NAME INTO NM
FROM (
SELECT DISTINCT NAME,
ROWNUM rnum
FROM MYTABLE
ORDER BY NAME DESC
)
WHERE rnum = r;
dbms_output.put_line (NM);
END LOOP;
END;
I'd use an implicit cursor loop instead, they're very easy to work with.
FOR r in (SELECT DISTINCT NAME
FROM MYTABLE
ORDER BY NAME DESC)
LOOP
NM := r.NAME;
dbms_output.put_line (NM);
END LOOP;