首页 > 代码库 > 递归插入的应用(生成日历数据)
递归插入的应用(生成日历数据)
ALTER PROCEDURE usp_Calendar @StartDate DATE=‘2016-01-01‘, @EndDate DATE=‘2016-12-31‘ AS BEGIN ---------b)建表---------------------------------------- /* /****** Object: Table [dbo].[Calendar] Script Date: 2016/10/20 16:17:40 Created By Vison.Ding ******/ SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[Calendar]( [DateKey] int NOT NULL, [FullDateAlternateKey] date NOT NULL, [DayNumberOfWeek] tinyint NOT NULL, [DayNumberOfMonth] tinyint NOT NULL, [DayNumberOfYear] smallint NOT NULL, [WeekNumberOfYear] tinyint NOT NULL, [Week] NVARCHAR(3) NOT NULL, [MonthNumberOfYear] tinyint NOT NULL, [CalendarQuarter] tinyint NOT NULL, [CalendarYear] smallint NOT NULL, [CalendarSemester] tinyint NOT NULL, CONSTRAINT [PK_Calendar_DateKey] PRIMARY KEY CLUSTERED ( [DateKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY], CONSTRAINT [AK_Calendar_FullDateAlternateKey] UNIQUE NONCLUSTERED ( [FullDateAlternateKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] --*/ ---------b)递归插入---------------------------------------- --DECLARE @StartDate DATE=‘2016-01-01‘, -- @EndDate DATE=‘2016-12-31‘ ;WITH CTE(ID, [FullDateAlternateKey]) AS ( SELECT 1, CONVERT(DATE, @StartDate) UNION ALL SELECT ID+1, DATEADD(DD, 1, [FullDateAlternateKey]) FROM CTE WHERE [FullDateAlternateKey] < @EndDate ) INSERT INTO [Calendar]([DateKey], [FullDateAlternateKey], [DayNumberOfWeek], [DayNumberOfMonth], [DayNumberOfYear], [WeekNumberOfYear], [Week], [MonthNumberOfYear], [CalendarQuarter], [CalendarYear], [CalendarSemester] ) SELECT REPLACE([FullDateAlternateKey], ‘-‘, ‘‘) AS [DateKey] ,[FullDateAlternateKey] ,DATEPART(W, [FullDateAlternateKey]) AS [DayNumberOfWeek] --一周中第几天 ,DATEPART(DD, [FullDateAlternateKey]) AS [DayNumberOfMonth] --多少号 ,DATEPART(DY, [FullDateAlternateKey]) AS[DayNumberOfYear] --一年中第多少天 ,DATEPART(WEEK, [FullDateAlternateKey]) AS [WeekNumberOfYear] --第几周 ,DATENAME(weekday, [FullDateAlternateKey]) AS [Week] --星期几 ,DATEPART(MM, [FullDateAlternateKey]) AS [MonthNumberOfYear] --月份 ,DATEPART(Q, [FullDateAlternateKey]) AS [CalendarQuarter] --季度 ,DATEPART(YYYY, [FullDateAlternateKey]) AS [CalendarQuarter] --年 ,CASE WHEN DATEPART(Q, [FullDateAlternateKey]) IN(1, 2) THEN 1 WHEN DATEPART(Q, [FullDateAlternateKey]) IN(3, 4) THEN 2 END AS [CalendarSemester]--半年 FROM CTE OPTION (MAXRECURSION 0) END
递归插入的应用(生成日历数据)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。