创建日历日表

时间:2017-03-31 03:16:39

标签: sql sql-server datetime calendar dateadd

我正在尝试编写一个我可以插入日期的代码,下面的表格将填充预期日期表,其中包含特定月份的所有日期,从CD1(日历第1天)一直到CD30或CD31或二月案例CD28。我知道我应该用

之类的东西开始我的代码
Declare @startdate as datetime
Set @startdate = '20170401'

但之后我对DateAdd和DatePart代码感到困惑,以创建此查询以生成结果

date rule  | expected date | 
----------------------------
| CD1      | 4/1/2017      |  
| CD2      | 4/2/2017      | 
| CD3      | 4/3/2017      |   
| CD4      | 4/4/2017      |   
| CD5      | 4/5/2017      | 
| CD6      | 4/6/2017      | 

任何人都可以提供任何帮助吗?

3 个答案:

答案 0 :(得分:1)

试试这个,

Declare @startdate as datetime
Set @startdate = '20170401'

;with cte as
(
select @startdate dt,1 ruleid
union ALL
select dateadd(day,1,dt)
,ruleid+1
from cte    
where 
dt<dateadd(day,-1,dateadd(month, datediff(month,0,@startdate)+1,0))
)

select *,'CD'+cast(ruleid as varchar) CalenderRule

 from cte

答案 1 :(得分:0)

DECLARE @startdate datetime = '2017-04-01'
DECLARE @startdate_for_loop datetime
SET @startdate_for_loop = @startdate

CREATE TABLE #T (date_rule nvarchar(100), exp_date datetime)
declare @x int = 1
WHILE MONTH(@startdate) = MONTH(@startdate_for_loop)
BEGIN
 INSERT INTO #T VALUES ('CD' + CAST(@x as nvarchar(max)), @startdate_for_loop)
 SET @x = @x + 1
 SET @startdate_for_loop = DATEADD(DD, 1, @startdate_for_loop)
END


SELECT * FROM #T

答案 2 :(得分:0)

尝试以下查询,这将为您提供所需的输出:

DECLARE @STARTDATE DATETIME
SET @STARTDATE= CAST(MONTH(CURRENT_TIMESTAMP) AS     VARCHAR(100))+'/'+'01'+'/'+CAST(YEAR(CURRENT_TIMESTAMP) AS VARCHAR(100))
;WITH MONTHDATA
AS
(SELECT @STARTDATE MONTHDATE
UNION ALL
SELECT DATEADD(D,1,MONTHDATE) FROM MONTHDATA WHERE     MONTHDATE<DATEADD(D,-1,DATEADD(M,1,@STARTDATE))
)
SELECT 'CD'+CAST( (ROW_NUMBER()OVER (ORDER BY MONTHDATE)) AS         VARCHAR(100))DATE_RULE,CONVERT(VARCHAR,MONTHDATE,101)MONTHDATE FROM MONTHDATA

输出

----------------------
DATE_RULE   MONTHDATE
----------------------
CD1 03/01/2017
CD2 03/02/2017
CD3 03/03/2017
.
.
.
CD29    03/29/2017
CD30    03/30/2017
CD31    03/31/2017
----------------------