0

I have a table in database. Sometimes (for example, 1 time in a month) I need to fill it with 10 rows of generated NONREPEATABLE codes (like password or promo).

Length - 10

Chars - 0..9, 'A'..'Z'

Table's columns: id, code

Hope for some help Thanks

[EDITED]

I have found the way by using this tutorial How to generate unique promotion... on PHP...

Thanks everybody answered )

3
  • What RDBMS do you use? i.e. Oracle, SQL Server etc. Also, does this need to be in pure SQL or would you be happy with a solution in a programming language? Oct 10, 2013 at 6:59
  • @ChrisProsser I use MySQL+PHP+iPad Application. So through php-script I would like to check the list of codes. Filling method not in the iPad app, so I would like do that myself by sql (or may be php) script
    – Romowski
    Oct 10, 2013 at 7:53
  • Er, given mt_rand() isn't considered cryptographically secure, the output of the function can be (theoretically) predicted. From the documentation you may want to look into a different function. Note that this may not be terribly important if your site is small/promotions not as enticing. Oct 10, 2013 at 10:04

1 Answer 1

0
select cast((Abs(Checksum(NewId()))%10) as varchar(1)) + 
   char(ascii('a')+(Abs(Checksum(NewId()))%25)) +
   char(ascii('A')+(Abs(Checksum(NewId()))%25)) +
   left(newid(),5)

from yourTable Try this

1
  • ...you're ignoring a huge portion of allowed values, given that you have 1 leading digit, followed by a single upper and lower case letter, then (probably) 5 more digits - for a maximum of 8 characters (not the requested 10)... and that's the least of the problems here. Going off of experience with other RDBMSs, NEWID() is likely generating sequential ids from the given table, which is going to reduce the 'randomness' of the result to practically 0. Note that doing this in SQL is often difficult - much easier to use a HLL which has cryptographic features. Oct 10, 2013 at 9:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.