时间维度表的存储过程

代码如下:

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'

效果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值