Archive for May 21st, 2008

May 21 2008

SQL Alphanumeric Unique Keys

Published by Raja Nadar under .net

a small SQL snippet to generate a unique alphanumeric key. you have to feed in an existing key value and the script will give you the next value.

i had written this snippet way back, for a legacy application in which a simple GUID or auto-incrementing big ineteger could not be used as the primary key.

i just rewrote it in the Katmai IDE, and the first feel of native intellisense in SQL studio is refreshing.

here goes the snippet:

 

Declare @currentKey varchar(32)
Declare @nextUniqueKey varchar(32)
Declare @currentKeyLength int
Declare @counter int
Declare @newKeyHasCarry bit
Declare @singleChar char(1)
 
-- Let us assume, we have a current key and we are looking for
-- the next incremental unique key.
SELECT @currentKey =  'Test129'
 
SET @currentKey = UPPER(@currentKey)
SELECT @currentKey	    
 
-- Logic to build the incremented AlphaNumeric key value, which is unique.
 
SET @counter = 0
SET @nextUniqueKey = ''
SET @newKeyHasCarry = 0
SET @currentKeyLength = Len(@currentKey)
 
-- Iterate through each character in our current key to find the increment.
-- We'll have a carry, if we see '9' as the last character.
While @counter <= @currentKeyLength
Begin
 
SET @singleChar = SubString(@currentKey, @currentKeyLength-@counter, 1)
 
-- We need to increment only if there is a carry, or if it is our first iteration.
IF (@newKeyHasCarry = 1) OR (@counter=0)
Begin
        -- Increment 9 to 'A'
		IF IsNumeric(@singleChar) = 1
		Begin
				IF @singleChar = '9'
					 Begin
					  SET @singleChar = 'A'
					  SET @newKeyHasCarry = 1
					 End
				Else
					 Begin
					  SET @singleChar = @singleChar + 1
					  SET @newKeyHasCarry = 0
					 End
		 End
		Else
		Begin
 
			IF @singleChar='Z'
			 Begin
			  SET @singleChar = '0'
			 End
			Else
			 Begin
			  SET @singleChar = Char(ASCII(@singleChar) + 1)
			 End 
 
			SET @newKeyHasCarry = 0
		End
End
 
-- Append the new character, to construct the key in a reverse direction.
SET @nextUniqueKey = Cast((@nextUniqueKey + @singleChar) AS varchar(255))
SET @counter = @counter + 1
End
 
-- Reverse the key to get the proper unique key.
SET @nextUniqueKey = Reverse(@nextUniqueKey)
 
SELECT UPPER(@nextUniqueKey)
-- End of snippet
-- End of snippet

Notes:

  1. After ‘Z’, the next incremental character is assumed to be ‘0′ [zero]
  2. The snippet is case insensitive.
  3. I like the in-built intellisense of SQL 2008. getting rid of external tools is nice.

 

there’s a solution to every problem; given enough time and money..

No responses yet