Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Database Design and Application Architecture
 generate random and unique number within sql ?

Author  Topic 

BitShift
Yak Posting Veteran

98 Posts

Posted - 2007-12-11 : 12:04:30
I need to generate a random 10 digit alphanumeric string that is also unique within a table. My application will be calling a stored procedure to insert this number into the table. This number will be associated with a id from another table. Is it better to generate the random number within sql (and perform the lookup at the same time), then just pass the number back to the calling application ?

If the calling application generates the number, it will also need to make a call to check if its unique. So im thinking it would be best to simply have sql generate this random number, check the number against the table and then insert the new record.

thoughts ?

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2007-12-11 : 12:07:51
select left(replace(cast(newid() as varchar(36)), '-', ''), 10)

_______________________________________________
Causing trouble since 1980
blog: http://weblogs.sqlteam.com/mladenp
SSMS Add-in that does a few things: www.ssmstoolspack.com <- new version out
Go to Top of Page

jezemine
Master Smack Fu Yak Hacker

2886 Posts

Posted - 2007-12-11 : 12:26:43
you aren't using letters bigger than F. got something against G? H?

you must be a letterist.



EDIT: have a look here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=59194


elsasoft.org
Go to Top of Page

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2007-12-11 : 12:45:03
I Stop at F. it's a matter of principle

_______________________________________________
Causing trouble since 1980
blog: http://weblogs.sqlteam.com/mladenp
SSMS Add-in that does a few things: www.ssmstoolspack.com <- new version out
Go to Top of Page

BitShift
Yak Posting Veteran

98 Posts

Posted - 2007-12-11 : 14:10:18
Thanks a bunch guys, I had forgot about newid( )

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-12-11 : 14:13:54
You can cast the NEWID() as bigint if you want unique numeric value.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -