Link to home
Start Free TrialLog in
Avatar of websss
websssFlag for Kenya

asked on

sql query to create new records from 0001 to 9999

As the title suggests, i need to create a new table call CardPool

In this table i need the following structure

CardNumber (4 digits unique number) clustered
ActiveStatus (bit) default 0

then in the table i need to have the rows from 0001 to 9999
i,e,
0001
0002
0003
...
9998
9999

Does anyone know the correct script to generate this?
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

there are other ways to do ...
;with data as (select 1 n union all select n + 1 from data where n < 9999 )
select right('000' + cast(n as varchar(10)), 4) from data
option (maxrecursion 10000)

Open in new window

;with digits as (select '0' n 
union all select '1'
union all select '2'
union all select '3'
union all select '4'
union all select '5'
union all select '6'
union all select '7'
union all select '8'
union all select '9'
)
select d1.n + d2.n + d3.n + d4.n
 from digits d1, digits d2, digits d3, digits d4
where d1.n + d2.n + d3.n + d4.n <> '0000'
order by 1

Open in new window

of course, the above is only the SELECT part, which you can use to actually INSERT into your table
Avatar of websss

ASKER

Thanks,
I'm not sure how this works as i cannot see inserting into the CardNumber column?
the syntax, from above, would be in general:
;WITH alias AS ( <some query> )
INSERT INTO yourtable ( <columns> )
SELECT <columns>
  FROM alias

so, taking my first query sample:
;with data as (select 1 n union all select n + 1 from data where n < 9999 )
INSERT INTO CardPool ( CardNumber ) 
select right('000' + cast(n as varchar(10)), 4) 
from data
option (maxrecursion 10000) 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial