Shashi Dhar
Shashi Dhar

Reputation: 633

print a char in sqlserver in a same line within while loop

I need to produce

*    
**     
***    
****    
*****    

as output in sql server

DECLARE @x INT ;
DECLARE @y INT ;

SET @x = 1;
set @y=0;

while @x <=5
begin
while @y<@x
    begin
    print('*')
    set @y=@y+1
    end
print ''+char(1)
set @y=0;
set @x=@x+1
end

But I can't print * in the same line each * is printing in individual line

Upvotes: 0

Views: 5492

Answers (5)

Kavindu Tharaka
Kavindu Tharaka

Reputation: 279

Try inbuilt Replicate() method in SQL SERVER

DECLARE @var int                
SET @var = 1   

DECLARE @rows int  /*number of rows you want*/
SET @rows = 5 

WHILE (@var <= @rows)   
BEGIN                       
  PRINT Replicate('*', @var)     
  SET @var = @var + 1            
END 

more details : https://www.w3schools.com/sql/func_sqlserver_replicate.asp

Upvotes: 1

Sean Lange
Sean Lange

Reputation: 33581

Here is another option that doesn't use looping. In the real world a tally/numbers table would make short work of this.

select replicate('*', n)
from
(
    values(1),(2),(3),(4),(5)
) x(n)

Upvotes: 3

Chanukya
Chanukya

Reputation: 5893

You can try like this

;WITH nums AS
       (SELECT 1 AS value
        UNION ALL
        SELECT value + 1 AS value
        FROM nums
        WHERE nums.value <=5)
    SELECT replicate('*',value)
    FROM nums 

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270401

This seems like a silly inner loop when you can just do:

print replicate('*', 5)

and put that into a loop (if you want print instead of select).

set @x = 1;

while @x <=5
begin
    print replicate('*', @x);
    set @x = @x + 1;
end;

Upvotes: 3

Brad
Brad

Reputation: 3591

You can create a variable and populate that with what you want to print, and then print that after all your loops.

See code below, I commented out your prints and used variables instead.

DECLARE @x INT ;
DECLARE @y INT ;
DECLARE @ValueToPrint VARCHAR(MAX) = ''

SET @x = 1;
set @y=0;

while @x <=5
    begin
        WHILE @y<@x
            BEGIN
                SET @ValueToPrint += '*'
                --print('*')
                SET @y=@y+1
            END


        SET @ValueToPrint += ''+char(1)
        --PRINT ''+char(1)
        -- maybe you want to print it here, if so print the variable here if so uncomment these 2 lines
        -- PRINT @ValueToPrint
        -- SET @ValueToPrint = ''

        SET @y=0;
        SET @x=@x+1
    END

PRINT @ValueToPrint

Upvotes: 0

Related Questions