----------------------------------------------------------------
--                                                              
--  File:   Get_Next_T_ID.SQL                                   
--          Microsoft TPC-E Benchmark Kit Ver. 1.14.0-1031      
--          Copyright Microsoft, 2008-2015                  
--                                                              
----------------------------------------------------------------
USE tpce
GO

---
--- Set connection attributes
---
SET ANSI_NULLS ON
SET ANSI_NULL_DFLT_OFF OFF
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET NUMERIC_ROUNDABORT OFF
GO

IF EXISTS ( SELECT name FROM sysobjects WHERE name = 'Get_Next_T_ID' )
    DROP PROCEDURE Get_Next_T_ID
GO

CREATE PROCEDURE Get_Next_T_ID
                        @next_t_id       bigint  OUTPUT
AS
BEGIN
    DECLARE @max_t_id   bigint
    
    SET     @next_t_id  = NULL

    -- get the next value for this SPID
    UPDATE  TID_RANGES
    SET     @next_t_id  = NEXT_T_ID,
            NEXT_T_ID   = NEXT_T_ID + 1
    WHERE   SPID        = @@spid AND
            NEXT_T_ID   <= MAX_T_ID

    -- in the normal case, we are done
    IF @next_t_id IS NOT NULL RETURN
    
    -- getting this far indicates that either there is not an entry in TID_RANGES for this SPID or
    -- the end of the range was reached.
    -- both the above cases are handled below
    UPDATE  TID_RANGES
    SET     @next_t_id  = NEXT_T_ID,
            @max_t_id   = NEXT_T_ID + MAX_T_ID - 1,
            NEXT_T_ID   = NEXT_T_ID + MAX_T_ID
    WHERE   SPID        = -1

    -- if it exists, delete the entry for the current SPID
    DELETE  FROM TID_RANGES
    WHERE   SPID    = @@spid

    -- insert a new entry for the current SPID
    INSERT  INTO TID_RANGES VALUES (@@spid,
                                    @next_t_id + 1,
                                    @max_t_id)

END
GO
