Reputation:
I want some PL/SQL code which prints 1 to 100. Additionally for numbers divisible by 3 print 'wel'
, for numbers divisible by 5 print 'come'
and for numbers divisible by 3 and 5 then print 'welcome'
. Output like this
1
2
wel
4
come
7
.
.
14
welcome
Here is some code I have written:
begin
for i in 1..100 loop
dbms_output.put_line(i);
if mod(i,3)=0 then
dbms_output.put_line('wel');
elsif mod(i,5)=0 then
dbms_output.put_line('come');
elsif mod(i,3)=0 and mod(i,5)=0 then
dbms_output.put_line('welcome');
end if;
end loop;
end;
/
Upvotes: 1
Views: 1027
Reputation: 175586
It looks like variation of Fizzbuzz interview question. You could use single query:
SELECT nvl(decode(mod(rownum,3),0,'wel')||decode(mod(rownum,5),0,'come'),rownum)
as Example
FROM xmltable('1 to 100');
PL/SQL block:
BEGIN
FOR i IN (
SELECT nvl(decode(mod(rownum,3),0,'wel')||decode(mod(rownum,5),0,'come'),rownum)
as Example
FROM xmltable('1 to 100')) LOOP
DBMS_OUTPUT.PUT_LINE(i.Example);
END LOOP;
END;
As you posted your code is is very easy to fix it:
begin
for i in 1..100 loop
if mod(i,3)=0 and mod(i,5)=0 then
dbms_output.put_line('welcome');
elsif mod(i,5)=0 then
dbms_output.put_line('come');
elsif mod(i,3)=0 then
dbms_output.put_line('wel');
else
dbms_output.put_line(i);
end if;
end loop;
end;
//
Upvotes: 4