1

I just want to generate a list like this

XY0001  
XY0002  
XY0003  

The prefix is same for all rows. Need fixed length (6 in this example)
Looking for an easy way to produce such list to put it into temp table.

MS SQL

for a very small number this would do:

DECLARE @TempList TABLE (Name VARCHAR(100));  
insert into @TempList Values ('XY00001')   
insert into @TempList Values ('XY00002')   
insert into @TempList Values ('XY00003')   
insert into @TempList Values ('XY00004')   


select * from @TempList  
1
  • please tag the dbms you are using and also clarify what you mean by list Commented Mar 12, 2017 at 17:07

2 Answers 2

1

You can use an ad-hoc tally table

If 2012+

DECLARE @TempList TABLE (Name VARCHAR(100)); 

Select Name = 'XY'+format(N,'0000')
 From (Select Top 9999 N=Row_Number() Over (Order By (Select NULL)) From master..spt_values N1,master..spt_values N2) A
 Order by N

Returns

Name
XY0001
XY0002
XY0003
XY0004
...
XY9997
XY9998
XY9999

If not

DECLARE @TempList TABLE (Name VARCHAR(100));

Select Name = 'XY'+right('00000'+cast(N as varchar(25)),4)
 From (Select Top 9999 N=Row_Number() Over (Order By (Select NULL)) From master..spt_values N1,master..spt_values N2) A
 Order by N
Sign up to request clarification or add additional context in comments.

2 Comments

The first Approach works immediately and is pretty short, which is good in my opinion. Only disadvanatge is, that I don't understand ;-)
@Volker Just run the sub-query, you'll see that it just generates a list of numbers. A tally/numbers table will do the trick as well. --- Happy it helped
0

I like to use recursive CTE's for this.

declare @max_number int = 1000;

with num as (
  select 1 as n
  union
  select n + 1
  from num
  where n < @max_number
)
select 'XY' + (cast n as char(4))
from num;

The recursive CTE gives you the numbers and the cast does the left-padding with 0's to ensure you get 0001 instead of 1.

This approach will support a variable number of outputs. Though as you alluded to in your question, this is overkill if you only want a few.

(You'll need to test this out for boundary cases. I haven't tested this exact code sample.)

There is likely a limit to how far this scales because it uses recursion.

1 Comment

This one Looks very good to me and I could adjust it with my knownledge to my Situation. Unfortunately it does not work (Syntax error) ;-(

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.