0

I am trying to replicate the following code in SQL Server to PostgreSQL:

declare @row int = 1
while (@row < 6)
begin
    print replicate('* ', @row)
    set @row = @row + 1
end;

Required output

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

2 Answers 2

2

You can use generate_series()

select rpad('*', i, '*')
from generate_series(1,5) as g(i)

Online example

Sign up to request clarification or add additional context in comments.

3 Comments

I just tested in pgAdmin and it works. Thanks a lot.
A small follow up question, how to print in reverse? i.e. 5stras, 4stars, etc.
@MilkyWay001: switch the order of generate_series()dbfiddle.uk/…
2

Loops should be avoided when possible. In SQL Server, you can use an ad-hoc tally table

Example

Select Top (5) Stars=replicate('*',Row_Number() Over (Order By (Select NULL))) 
 From  master..spt_values n1

Returns

Stars
*
**
***
****
*****

EDIT - Descending Order

Select Stars = replicate('*',N)
 From (Select top (5) N=Row_Number() Over (Order By (Select NULL)) From  master..spt_values n1 ) A
 Order By N Desc

7 Comments

@MilkyWay001 It really does work in SQL Server. I was really demonstrating that loops should be avoided. The SQL Server option would be as above See dbfiddle.uk/…
Thanks John, it works in sql-server but I was trying to replicate this in postgresql.
How to print in reverse order like 5 stars, 4stars, etc in ms-server (I guess you prefer ms-server)?
@MilkyWay001 Take a peek at stackoverflow.com/questions/61125707/…
Thanks a lot. That's a lot of advanced than I expected. I need to brush up more of my SQL skills.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.