Anonymized block help with IF in PL/SQL

Asked

Viewed 121 times

-1

I am studying PL/SQL on my own account and I am having a lot of difficulty, I would like to tell you how I can improve the code below. I’m using the logic of wanting to pull and count every time the letter "M" appears in the table below. It’s just that you’re making a mistake on the Else part, if anyone has any tips on how to improve the code, or how best to do this.inserir a descrição da imagem aqui

`declare 
 contador NUMBER;
 contador2 NUMBER;
begin
SELECT SEX FROM EMPLOYEE;
contador := 0;
contador2 := 0;
 if EMPLOYEE.SEX = 'M'  
   then loop 
       contador := contador + 1;
      else 
      contador := contador2 + 1;
   end if;
   end loop;
   DBMS_OUTPUT.PUT_LINE('Numero de sexo Masculino é', contador, 
   'Numero de sexo feminino é', contador2);
end`
  • do not program in pl/sql, however, seeing the documentation, the IF structure does not seem to have this loop.

  • the loop is not really part of it, but it is allowed by pl/sql to loop inside IF’s and Else, in which case I used it because I am increasing the counters to know how many times M or F appears inside the column

  • maybe on the line contador := contador2 + 1 shouldn’t be contador2 := contador2 + 1?

  • I think you are mistakenly considering that your loop will run through the lines resulting from the select. See cursor or, better yet, use an aggregation function in select.

  • I managed to settle here with FOR with the help of a staff of my company, I will post the code

  • but thanks for the help and tips

Show 1 more comment

1 answer

0

    declare 
 contador NUMBER := 0;
 contador2 NUMBER := 0;
begin
 for REG in(Select * FROM EMPLOYEE)LOOP 
  if REG.SEX = 'M' then
  contador := contador + 1;
  else
  contador2 := contador2 + 1;
  end if;
  end LOOP;
  DBMS_OUTPUT.put_line('Masculino: 'contador' Feminino: ' contador2); 

end;

In the above way I solved with the FOR and the bottom was what guided me doing with only one SELECT.

SELECT SEX, COUNT(1) FROM EMPLOYEED GROUP BY SEX;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.