Generate a unique random integer in the database column

My application creates coupons, each of which needs a unique barcode number. This number must be a positive integer and must be between 6 and 12 digits. This number is a unique coupon, so this number must be unique. I can't just increase the number of barcodes by 1, because it will allow hackers to guess other coupon barcodes.

If I have a coupon db table, how can I generate this random barcode number and guarantee uniqueness?

+5
source share
2 answers

This will give you a random number of up to 12 digits with very few conflicts.

select -convert(bigint, convert(varbinary(max), newid())) % 1000000000000

You need to test and ignore conflicts, and also discard numbers that end in less than 6 digits.


EDIT

, . , , 95% 6- , , , , . , "" . , " ", , (order by len(num), newid()) , .

0-pad 12

select right('000000000000'
      +right(-convert(bigint, convert(varbinary(max), newid())),12),12)
+5

, , , , ( 6-12 ) . 12 - , , , .

+2

All Articles