1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/* This stored procedure combines any overlapping time segments into
a single segment in the temporary table #CombinedTime. Only non-
overlapping segements of time exist in this table. It then returns the
total hours for all these remaining segments.
Assumptions:
1. Date_Start <= Date_End
2. Date_Start, and Date_End are not null
Usage:
DECLARE @Total_Hours AS INT
EXEC @Total_Hours = CombinedTime
PRINT @Total_Hours
*/
ALTER PROCEDURE [dbo].[CombinedTime]
@IdAidant char(14)
AS
DECLARE
@Date_Start AS SMALLDATETIME,
@Date_End AS SMALLDATETIME,
@Total_Hours AS INT
/* Create temporary table to contain combined information.
*/
CREATE TABLE #CombinedTime (
Date_Start SMALLDATETIME NOT NULL ,
Date_End SMALLDATETIME NOT NULL
)
/* Use a cursor to get every record from Session_Temp */
DECLARE Time_Cursor CURSOR FOR
SELECT DateDebut, DateFin
FROM Evenement WHERE (IdAidant = @IdAidant AND DateDebut BETWEEN '20120126 00:00:00' AND '20120126 23:59:00')
ORDER BY DateDebut ASC
OPEN Time_Cursor
FETCH NEXT FROM Time_Cursor INTO @Date_Start, @Date_End
WHILE (@@FETCH_STATUS != -1)
BEGIN
/* Update an existing record in the temporary table if Date_Start is
within the bounds of an existing record, and the Date_End is outside */
UPDATE #CombinedTime
SET Date_End = @Date_End
WHERE @Date_Start BETWEEN Date_Start AND Date_End
AND @Date_End > Date_End
/* Insert a record that falls completely outside previous ranges */
INSERT INTO #CombinedTime
(Date_Start, Date_End)
SELECT @Date_Start, @Date_End
WHERE NOT EXISTS (SELECT 1
FROM #CombinedTime
WHERE @Date_Start < Date_End)
FETCH NEXT FROM Time_Cursor INTO @Date_Start, @Date_End
END /* WHILE */
CLOSE Time_Cursor
DEALLOCATE Time_Cursor
/* Get the total hours from the non-overlapping segments */
SELECT @Total_Hours = SUM(DATEDIFF(mi, Date_Start, Date_End))
FROM #CombinedTime
DROP TABLE #CombinedTime
RETURN @Total_Hours |
Partager