SqlServer create a time dimension

DECLARE @BeginDate DATE;

SELECT  @BeginDate  =  ' 2018-1-1 ' ;
WHILE  @BeginDate  <=  ' 2021-12-31 ' 
BEGIN 
INSERT  INTO Dim_Date
 SELECT  Cast ( CONVERT ( varchar ( 10 ), @BeginDate , 112 ) AS  INT ) AS DateKey,
        Year ( @BeginDate )                                    AS  Year ,
        DatePart (QUARTER, @ BeginDate)                       The AS Quarter,
        the CASE 
         the WHEN  Datepart (QUARTER, @BeginDate ) =  . 1  THEN  ' first quarter ' 
         the WHEN  Datepart (QUARTER, @BeginDate ) =  2  THEN  ' second quarter ' 
         the WHEN  Datepart (QUARTER, @BeginDate ) =  . 3  THEN  ' of three quarters of ' 
         the ELSE  ' quarter ' 
       the END                                                 the AS QuarterCN,
        Month ( @BeginDate)                                   The AS  Month ,
        the CASE 
         the WHEN  Month ( @BeginDate ) =  . 1  THEN  ' Jan ' 
         the WHEN  Month ( @BeginDate ) =  2  THEN  ' February ' 
         the WHEN  Month ( @BeginDate ) =  . 3  THEN  ' March ' 
         the WHEN  Month ( @BeginDate ) =  . 4  THEN  ' April ' 
         the WHEN  Month( @BeginDate ) =  . 5  THEN  ' May ' 
         the WHEN  Month ( @BeginDate ) =  . 6  THEN  ' June ' 
         the WHEN  Month ( @BeginDate ) =  . 7  THEN  ' Jul ' 
         the WHEN  Month ( @BeginDate ) =  . 8  THEN  ' August ' 
         the WHEN  Month ( @BeginDate ) =  . 9  THEN  ' September ' 
         the WHEN Month ( @BeginDate ) =  10  THEN  ' 10月' 
         WHEN  Month ( @BeginDate ) =  11  THEN  ' 11月' 
         ELSE  ' 12月' 
       END    
                                                    AS MonthCN,
        CASE 
         WHEN  Date Part ( DAY , @BeginDate ) <=  10  THEN  1 
         WHEN  Date Part ( DAY , @BeginDate ) >  20  THEN  3 
         ELSE 2 
       END                                                 AS Ten,
           CASE 
         WHEN  Date Part ( DAY , @BeginDate ) <=  10  THEN  ' 上旬' 
         WHEN  Date Part ( DAY , @BeginDate ) >  20  THEN  ' 下旬' 
         ELSE  ' 中旬' 
       END                                                 AS TenCN,
        Date Part (WEEK, @BeginDate ) AS Week
        DATE NAME (Weekday, @BeginDate ) ASWeekday,
        Day ( @BeginDate ) AS  Day ,
        CONVERT ( VARCHAR ( 10 ), @BeginDate , 120 ) AS Date
     SET  @BeginDate  =  DATEADD ( DAY , 1 , @BeginDate );     
 
  END;

 

Guess you like

Origin www.cnblogs.com/wwh/p/12334249.html