skip to Main Content

We got to print ‘*’ 20 times followed by 19 times and so on till we only got to print 1!

delimiter $$
create procedure test()
begin
    set @ans = 20;
    while(@ans>0) do
        select repeat('*',@ans);
        set @ans = @ans - 1;
    end while;
end $$
delimiter ;

call test();

This is getting the job done but also printing (repeat('*',@ans)) after each respective character line. What am I doing wrong?

2

Answers


  1. Is this what you want :

    You can add the alias you want in this exemple its *

    delimiter $$
    create procedure test()
    begin
        set @ans = 20;
        while(@ans>0) do
            select repeat('*',@ans) as '*';
            set @ans = @ans - 1;
        end while;
    end $$
    delimiter ;
    
    call test();
    
    Login or Signup to reply.
  2. Your stored procedure is performing a select statement 20 times and each select statement has its own result-set, so this is what causes what you said: printing (repeat(‘*’,@ans)) after each respective character line.

    Instead, you could use a variable to store the populated strings inside the while loop, then select that variable outside the loop.

    create procedure test()
    begin
        set @ans = 20;
        set @res = '';
        while(@ans>0) do
            set @res= concat(@res , repeat('*',@ans), 'n'); -- you may replace 'n' with any other delimiter.
            set @ans = @ans - 1;
        end while;
    select @res as test_result;
    end 
    

    see demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search