首页 > 代码库 > 递归插入的应用(生成日历数据)

递归插入的应用(生成日历数据)

技术分享
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
View Code

 

递归插入的应用(生成日历数据)