Created
April 18, 2018 18:13
-
-
Save Cabeda/e977ba50e5a55d0ac1c211b011537ff3 to your computer and use it in GitHub Desktop.
Creates a sql date table for a specified interval (Portuguese column names)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GO | |
CREATE TABLE [dbo].[DimData] | |
( | |
DateID int not null PRIMARY KEY, | |
Ano int not null, | |
Semestre int not null, | |
Quadrimestre int not null, | |
Mes int not null, | |
Semana int not null, | |
DiadaSemana int not null, | |
Dia int not null, | |
FimdeSemana int not null, | |
Data date not null, | |
TipoDia int null | |
) ON [PRIMARY] | |
GO | |
DECLARE @minDate date = '20100101'; | |
DECLARE @endDate date = '20400101'; | |
WITH DateDimTbl (DateID, [Ano], Semestre, Quadrimestre, [Mes], [Semana], [DiadaSemana], [Dia],[FimDeSemana], [Data]) | |
AS | |
( | |
SELECT YEAR(@minDate) * 10000 + MONTH(@minDate) * 100 + DAY(@minDate) AS DateID | |
, YEAR(@minDate) AS [Ano] | |
, (MONTH(DATEADD(D, 1, @minDate))- 1) / 6 + 1 AS Semestre | |
, DATEPART(Q,@minDate) Quadrimestre | |
, MONTH(@minDate) AS Mes | |
, DATEPART(ww,@minDate) Semana | |
, DATEPART(dw,@minDate) DiadaSemana | |
, DAY(@minDate) Dia | |
, CASE WHEN DATEPART(dw,@minDate) BETWEEN 6 AND 7 THEN 1 ELSE 0 END FimdeSemana | |
, CAST(@minDate AS DATETIME) [Data] | |
UNION ALL | |
SELECT YEAR(DATEADD(D, 1, [Data])) * 10000 + MONTH(DATEADD(D, 1, [Data])) * 100 + DAY(dateADD(D, 1, [data])) | |
, YEAR(DATEADD(D, 1, [data])) | |
, (MONTH(DATEADD(D, 1, [data]))- 1) / 6 + 1 | |
, DATEPART(Q, DATEADD(D, 1, [data])) | |
, MONTH(DATEADD(D, 1, [data])) | |
, DATEPART(ww,CAST([Data] AS DATE)) [Week] | |
, DATEPART(dw,CAST([Data] AS DATE)) [WeekDay] | |
, DAY(DATEADD(D, 1, [Data])) | |
, CASE WHEN DATEPART(dw,CAST([Data] AS DATE)) BETWEEN 6 AND 7 THEN 1 ELSE 0 END [Weekend] | |
, DATEADD(D, 1, [Data]) | |
FROM DateDimTbl | |
WHERE DATEADD(D, 1, [Data]) <= CAST(CAST(YEAR(@endDate) as VARCHAR) + '1231' as DATE) | |
) | |
insert into DimData (DateID, Ano, Semestre, Quadrimestre, Mes, Semana, DiadaSemana, Dia, FimdeSemana, [Data]) | |
SELECT DateID, Ano, Semestre, Quadrimestre, Mes, Semana, DiadaSemana, Dia, FimdeSemana, [Data] | |
FROM DateDimTbl option(MAXRECURSION 32000 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment