sql server - Generate list of new unique random numbers in T-SQL -


i need stored procedure generate @n records, each unique random 8 digit number. number must not incremental , must not exist in table.

create table codes (     id uniqueidentifier primary key,     code int,     constraint uq_code unique(code)  ); 

i can generate random numbers:

declare @min int = 0,         @max int = 99999999,         @n int = 100;  select top (@n) floor(cast(crypt_gen_random(4) bigint) / 4294967296 * ((@max - @min) + 1)) + @min   sys.all_objects s1                cross join sys.all_objects s2; 

but i'm struggling figure out how atomically generate , insert @n numbers [codes] table whilst making provision avoid collisions. can done without loop?

update
"must not incremental" meant each call sp, don't want return "1, 2, 3, 4" or other common pattern. need able consume values incremental values exist generated @ different points in time rather sequentially.

you can use cte calculated codes, distinct , check if code exists in table:

;with cte_stream (     select         floor(cast(crypt_gen_random(4) bigint) / 4294967296 * ((@max - @min) + 1)) + @min code     sys.all_objects s1          cross join sys.all_objects s2; ) insert [codes] select distinct top (@n) s.code cte_stream s not exists (select * [codes] c c.code = s.code) 

so distinct helps avoid collision between new codes , exists avoid collisions existing codes in [codes] table, , order newid() helps random values new codes


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -