代码如下:
create table Dim_Date (
日期 datetime not null,
日期序号 int not null,
年份名称 nvarchar(20) not null,
年份序号 int not null,
季度名称 nvarchar(20) not null,
季度序号 int not null,
年季度名称 nvarchar(20) not null,
年季度序号 int not null,
月份名称 nvarchar(20) not null,
月份序号 int not null,
年月名称 nvarchar(20) not null,
年月序号 int not null
);
go
create procedure dbo.usp_Dim_date
(
@StartDate as datetime,
@EndDate as datetime
)
as
begin
set nocount on;
if (@StartDate is null)
begin
set @StartDate = DATEFROMPARTS ( year(getdate()), 1, 1 )
end
if (@EndDate is null)
begin
set @EndDate = DATEFROMPARTS ( year(getdate()), 12, 31 )
end
while (@StartDate <= @EndDate)
begin
insert into Dim_Date
(
日期 ,
日期序号,
年份名称,
年份序号,
季度名称 ,
季度序号 ,
年季度名称 ,
年季度序号,
月份名称 ,
月份序号,
年月名称 ,
年月序号
)
select
T1.日期, convert(char(8), T1.日期, 112) as 日期序号, concat(N'Y', T1.年份序号) AS 年份名称, T1.年份序号, concat(N'Q', T1.季度序号) as 季度名称,
T1.季度序号,
concat(N'Y', T1.年份序号, N'Q', T1.季度序号) AS 年季度名称,
T1.年份序号 * 100 + T1.季度序号 as 年季度序号,
concat(N'M', T1.月份序号) AS 月份名称,
T1.月份序号,
concat(N'Y', T1.年份序号, N'M', T1.月份序号) AS 年月名称,
T1.年份序号 * 100 + T1.月份序号 as 年月序号
from (
Values (@StartDate, YEAR(@StartDate), DatePART(q, @StartDate), month(@StartDate))
) AS T1 (日期, 年份序号, 季度序号,月份序号)
where
not exists (select * from Dim_Date where 日期 = T1.日期)
set @StartDate = dateadd(day, 1, @StartDate);
end
set nocount off;
end
go
EXEC [dbo].[Usp_Dim_Date] '2022-01-01','2022-10-10'
效果如下: