Search code examples
oracleplsqlcursor

how do I use if condition in cursor because our professor don't allow us use where clause in the select statement


Our question is showing all the countries that have names that are exactly 5 letter long. This is the cursor code and I want add if condition into it.

declare
cursor cursor_full is select * from country_cont;
begin
for counter in cursor_full 
loop 
dbms_output.put_line(counter.country|| ' ' || counter.continent);
end loop; 
end;

However my professor said that you can't using where clause within the select statement and you should display all the countries and continent.

so i tried this code:

declare
country varchar(50);
cursor cursor_full is select * from country_cont;
begin
if length(country)=5 then
for counter in cursor_full 
loop 
dbms_output.put_line(counter.country|| ' ' || counter.continent);
end loop; 
end if;
end;

the script output show that PL/SQL procedure successfully completed but nothing return in DBMS output

Hope someone can help me, I spent whole night to think about it,please!


Solution

  • Variable country doesn't contain any value, it is null so if condition is never true and loop is never executed. Sample data would help; meanwhile, see if this helps.

    begin
      for cur_r in (select * from country_cont) loop
        if length(cur_r.country) > 5 then
           dbms_output.put_line(cur_r.country|| ' ' || cur_r.continent);
      end loop; 
    end;
    

    Don't forget to set serveroutput on.