• laurie-789651 (8/28/2012)


    This will work for adding one at a time:

    --------------------------------------------------------------

    drop table #test;

    create table #test ( id varchar(13) );

    --------------------------------------------------------------

    declare @id varchar(13), @nextid varchar(13);

    select @id = max(id) from #test;

    select @nextid = case when left(@id, 8) = convert(varchar(8), getdate(), 112)

    then convert(varchar(8), getdate(), 112) +

    right('0000' + cast(cast(substring(@id, 9, 5) as int) +1 as varchar(5)),5)

    else convert(varchar(8), getdate(), 112) + '00001'

    end;

    insert into #test values ( @nextid );

    --------------------------------------------------------------

    select * from #test;

    --------------------------------------------------------------

    Ohhhh.... be careful Laurie. A whole lot can happen between the time you get the max id and the time you use it. On high usage systems (or "unlucky" times on low usage systems) you'll end up with duplicate ID's (and dupe errors if the column is unique) with that code. The "obvious fix' of using an explicit transaction will lead to hundreds of deadlocks per day.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)