Home Forums SQL Server 2005 T-SQL (SS2K5) Incrementing an indentity column (not set in SQL as being identity) RE: Incrementing an indentity column (not set in SQL as being identity)

  • To my knowledge there's nothing standard that'd do that for you. I've written similar functions in the past to do incrementing that included letters. Here's one of them that was very close (I chopped it up a bit to match your scenario).

    You can compare them for speed and accuracy if you'd like.

    /*

    =============================================================================================

    CREATE DATE: 05/22/2009

    LAST MODIFIED:05/22/2009

    CREATED BY:SETH PHELABAUM

    PURPOSE:Generates the next Alpha-Numeric code in sequence.

    NOTES:Will not re-use or fix gaps. If you manually insert a gap, you could be wasting thousands of codes.

    ASCII Numbers 65-90 are A-Z. ASCII 48-57 are 0-9.

    ISSUES:If an ANC ZZZ or higher ASCII value is put into the system, this thing will break. (Out of valid Numbers)

    It will still return something, but it will use bogus characters for A1.

    This would likely be sped up significantly if the MAX() was done outside of the function.

    =============================================================================================

    SELECT dbo.fn_GenNextANC()

    */

    ALTER FUNCTION fn_GenNextANC()

    RETURNS char(3)

    AS

    BEGIN

    DECLARE @MaxANC char(3),

    @A1int,

    @A2 int,

    @A3 int,

    @NewANCchar(3)

    --SET @MaxANC = RIGHT( LTRIM(RTRIM((SELECT MAX(ANCField) FROM YourTable))), 3)

    SET @MaxANC = 'KAZ'

    SELECT @A1 = ASCII(LEFT(@MaxANC,1)),

    @A2 = ASCII(LEFT(RIGHT(@MaxANC,2),1)),

    @A3 = ASCII(RIGHT(@MaxANC,1))

    IF @A3 < 90 -- Increments A3 by 1.

    SET @NewANC = (char(@A1) +

    char(@A2) +

    CASE WHEN @A3 = 57 THEN char(@A3+8) ELSE char(@A3+1) END ) -- Uses Numbers, skips bogus characters.

    ELSE

    BEGIN

    IF @A2 < 90 -- If A2 < 'Z', add 1 and use 0 for A3.

    SET @NewANC = (char(@A1) +

    CASE WHEN @A2 = 57 THEN char(@A2+8) ELSE char(@A2 + 1) END + -- Uses Numbers, skips bogus characters.

    char(48))

    ELSE

    SET @NewANC = (-- If A2 = 'Z', Increment A1 by 1, Use 0 for A2 and A3.

    CASE WHEN @A1 = 57 THEN char(@A1+8) ELSE char(@A1+1) END + -- Uses Numbers, skips bogus characters.

    char(48) +

    char(48))

    END

    RETURN(@NewANC)

    END

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]