Création table de temps

La requête suivante permet de créer une table d’heure avec SQL server :

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
CREATE TABLE [Clock]
(
    ClTime time,
    ClHourMinuteStr VARCHAR(5),
    ClHourStr VARCHAR(2),
    ClHour int,
    ClMinuteStr VARCHAR(2),
    ClMinute int
);
 
 
BEGIN
    DECLARE @heureStr VARCHAR(2);
    DECLARE @minuteStr VARCHAR(2);
    DECLARE @heureMinute VARCHAR(5);
    DECLARE @idHeureMinute INTEGER;
    DECLARE @hour integer = 0;
    DECLARE @hourMax integer = 23;
    DECLARE @minute integer = 0;
    DECLARE @minuteMax integer = 59;
 
    BEGIN
 
        WHILE @hour <= @hourMax
        BEGIN
   
            SET @heureStr = REPLACE(STR(@hour, 2), SPACE(1), '0')
   
            WHILE @minute <= @minuteMax
            BEGIN
       
                SET @minuteStr = REPLACE(STR(@minute, 2), SPACE(1), '0')
           
                SET @heureMinute = @heureStr + ':' + @minuteStr;

                INSERT INTO [Clock]
                SELECT convert(time, @heureMinute), @heureMinute, @heureStr, @hour, @minuteStr, @minute;
       
           
              SET @minute = @minute + 1 ;
       
            END

            SET @minute = 0;
            SET @hour = @hour+1;
   
        END
   
 
    END

END;

Création calendrier

La requête suivante permet de générer une table « Calendar » avec Sql Server du 01/01/1900 au 12/31/2999 :

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
SELECT
    convert(date , d ) as CalDate,
    DATEPART(YEAR, d) as CalYear,
    DATEPART(QUARTER,  d) as CalQuarter,
    DATEPART(MONTH,  d) as CalMonth,
    DATENAME(MONTH,    d) as CalMonthName,
    DATEPART(WEEK,     d) as CalWeekOfYear,
    CONVERT(CHAR(10),  d, 101) as CalDateStr,
    DATEPART(WEEKDAY,  d) as CalDayOfWeek,
    DATEPART(DAY,  d) as CalDayOfMonth,
    DATEPART(dy, d) as CalDayOfYear,
    CONVERT(VARCHAR(10), DATENAME(WEEKDAY, d)) as CalDayName,
    DATEPART(YEAR, d)*100+REPLACE(STR(DATEPART(MONTH,  d), 4), SPACE(1), '0') as CalYearMonth,
    DATEPART(YEAR, d)*10000+REPLACE(STR(DATEPART(MONTH,  d), 4), SPACE(1), '0')*100+DATEPART(DAY,  d) as CalYearDay,
    CASE WHEN REPLACE(STR(DATEPART(MONTH,  d), 4), SPACE(1), '0')*100+DATEPART(DAY,  d) IN (101, 501, 508, 714,815, 1101, 1225) THEN 1 ELSE 0  END as CalIsPublicHoliday,
    case when DATEPART(WEEKDAY,  d) in (6, 7) THEN 1 else 0 end as CalIsWeekEnd
    into dbo.Calendar
from
(
SELECT d = DATEADD(DAY, rn - 1, '19000101')
  FROM
  (
    SELECT TOP (DATEDIFF(DAY, '19000101', '29991231'))
      rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
    FROM sys.all_objects AS s1
    CROSS JOIN sys.all_objects AS s2
    ORDER BY s1.[object_id]
  ) A
) b;

create index IdxRefCalendar on dbo.[REF-Calendar](CalDate);