/* Instructions - Replace "dbo.yourTable" with the table you're using - Replace "ID" with the name of the identity column of the table - Replace "[DateTime]" with the name of the datetime column of the table - Replace "@CuttOff = '31 July 2014'" With the datetime you're after */ /* ** Need these values to do the binary seek into the table */ DECLARE @CuttOff DateTime ,@maxid INT ,@nextid INT ,@previd INT ,@minid INT ,@complete BIT ,@lowerDate DateTime ,@upperDate DateTime; /* ** First we set a few standard values ** The cuttoff which we want to find the first record for ** The max id of the table and half way between so we can iterate over the records in a binary fashion ** A completed flag so we know when to bail from the loop */ SELECT @CuttOff = '31 July 2014' ,@maxid = MAX(ID) ,@nextid = (MIN(ID) + MAX(ID)) / 2 -- This was an efficiency gain for me because all the values I needed were in the top half of the table. Otherwise need to get @minid = MIN(ID) then calculate @nextid ,@complete = 0 FROM dbo.yourTable WITH(NOLOCK); /* ** Now we can iterate by taking halves, divide and conquer our way to the correct record ** One assumption we need to make is that the [DateTime] field will increase as the ID increases ** Check to ensure that @nextid cannot slam the left edge and loop forever */ WHILE (@complete = 0 AND @nextid > 0) BEGIN /* Ensure that the value we're going to check exists */ SELECT @nextid = MIN(ID) FROM dbo.yourTable WITH(NOLOCK) WHERE ID >= @nextid; /* This allows us to check that we have the correct two records */ SELECT @lowerDate = [DateTime] FROM dbo.yourTable WITH(NOLOCK) WHERE ID = @nextid; SELECT @upperDate = [DateTime] FROM dbo.yourTable WITH(NOLOCK) WHERE ID = @nextid + 1; /* If we span the time frame we want then we have the correct record and can bail */ IF (@lowerDate < @CuttOff AND @upperDate >= @CuttOff) BEGIN SET @complete = 1; END /* The top value is too low so we need to look in the top half of the remaining result set */ ELSE IF (@upperDate < @CuttOff) BEGIN SELECT @minid = @nextid, @previd = @nextid; SELECT @nextid = (@nextid + @maxid) / 2; END /* The lower value is too high so we need to look in the lower half of the result set remaining */ ELSE IF (@lowerDate > @CuttOff) BEGIN SELECT @previd = @nextid, @maxid = @nextid; SELECT @nextid = (@nextid + @minid) / 2; END; END; SELECT @nextid + 1; /* The first record we need */