fabioms-br/sqlserver

Adicionei mais periodos e informar datas anos para geração.

Closed this issue · 2 comments

/* Idioma de geração */
SET LANGUAGE 'Brazilian'

/* 1. Criar tabela AD_CALENDARIO */
DROP TABLE IF EXISTS AD_CALENDARIO;
GO

CREATE TABLE AD_CALENDARIO
(
[DATA] DATE PRIMARY KEY,
[ANOREF] AS DATEPART(YEAR,[Data]),
[MESREF] AS REPLICATE('0', 2 - LEN(DATEPART(MONTH,[Data]))) + RTrim(DATEPART(MONTH,[Data])) ,
[DIAREF] AS REPLICATE('0', 2 - LEN(DATEPART(DAY,[Data]))) + RTrim(DATEPART(DAY,[Data])),
[DIAANOREF] AS DATEPART(DAYOFYEAR,[Data]),
[MESANOREF] AS CONCAT(REPLICATE('0', 2 - LEN(DATEPART(MONTH,[Data]))) + RTrim(DATEPART(MONTH,[Data])),'/',DATEPART(YEAR,[Data])) ,
[ANOMESREF] AS CONCAT(DATEPART(YEAR,[Data]),'/',REPLICATE('0', 2 - LEN(DATEPART(MONTH,[Data]))) + RTrim(DATEPART(MONTH,[Data]))) ,
[TRIMESTREREF] AS REPLICATE('0', 2 - LEN(DATEPART(QUARTER,[Data]))) + RTrim(DATEPART(QUARTER,[Data])),
[SEMANAANOREF]AS REPLICATE('0', 2 - LEN(DATEPART(WK,[Data]))) + RTrim(DATEPART(WK,[Data])),
[MESNOMEREF] AS DATENAME(MONTH, [Data]),
[DIANOMEREF] AS DATENAME(WEEKDAY, [Data]),
[ANOTRIMESTREREF] AS CONCAT(DATEPART(YEAR,[Data]),' - ',DATEPART(QUARTER,[Data]),'º Trismestre')
);

GO

/* 3. Inserir datas na tabela AD_CALENDARIO */

WITH DATAS (DATAMIN,DATAMAX) AS (

SELECT MIN(DATAMIN), MAX(DATAMAX) FROM (

SELECT DATEADD(year, -30, cast(getdate() as date)) as DATAMIN,  DATEADD(year, 30, cast(getdate() as date)) as DATAMAX -- Tabela de Movimentos 

) RS ---- Tabela virtual de período 

)
, CALENDARIO AS (

SELECT (SELECT DATAMIN FROM DATAS) AS [DATA], 1 AS [NIVEL] -- Data Ponto Inicial
    
UNION ALL

SELECT DATEADD(DAY, 1, [DATA]), [NIVEL] + 1 -- Ponto Recursive
FROM  CALENDARIO
WHERE [Data] < (SELECT DATAMAX FROM DATAS)  

)

INSERT INTO AD_CALENDARIO ([DATA])
SELECT [DATA] FROM CALENDARIO
OPTION (MAXRECURSION 0)

GO

SELECT * FROM [AD_CALENDARIO]

Muito bom👍

Alterações significativas, parabéns.