Home Forums SQL Server 7,2000 T-SQL Problem with Variables. SQL Server 2000 RE: Problem with Variables. SQL Server 2000

  • Personally, I do prefer (and use) the 'single-update' method to increment and return the next countervalue in one go. It makes it unnecessary to wrap in explicit transactions and such. It's physically impossible for the server to return the same counter to more than one caller.

    update  counterTable

    set     @nextid = nextId = nextId + 1

    where   counterQualifier = @counterQualifier

    The above method both increments the counter and assigns the incremented value to @nextid at the same time.

    However, if you want to do it the 'traditional' way for whatever reason, in order to protect the counter while 'in-process' (since it's two statements) you must do a few more things.

    BEGIN TRAN

    UPDATE counterTable

    SELECT the new value

    COMMIT

    Note that the order is critical here - UPDATE must be before the SELECT, and the two must also be within an explicit transaction in order to ensure that noone else sneaks in between and manages to select the newly updated value.

    /Kenneth