大家好,我正在研究某种会计系统,遇到了一些困难。阿卜杜勒·拉希德已经在这个网站上回答了这个问题。
这是代码
declare @sDate datetime,
@eDate datetime
select @sDate = '2013-02-21',
@eDate = '2013-04-25';
with CTE_TEST
as (
select @sDate SDATE,
DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, @sDate) + 1, 0)) EDATE
union all
select EDATE + 1,
DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(MONTH, 1, SDATE)) + 1, 0))
from CTE_TEST C
where DATEADD(MONTH, 1, SDATE) < DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, @eDate) + 1, 0))
)
select DATENAME(MONTH, SDATE) MNAME,
SDATE, (case when EDATE > @eDate then @eDate else EDATE end) EDATE
from CTE_TEST
代码很有效,就像我想要的那样。但我想将结果插入到新表中。我该怎么做?
答案 0 :(得分:2)
CREATE TABLE T(MNAME VARCHAR(20),SDATE DATETIME,EDATE DATETIME)
IF OBJECT_ID ('tempdb..#T') IS NOT NULL
DROP TABLE #T
declare @sDate datetime,
@eDate datetime
select @sDate = '2013-02-21',
@eDate = '2013-04-25'
;WITH CTE_TEST AS (
SELECT @sDate SDATE,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@sDate)+1,0)) EDATE
UNION ALL
SELECT EDATE+1,DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,DATEADD(MONTH,1,SDATE))+1,0))
FROM CTE_TEST C WHERE DATEADD(MONTH,1,SDATE) < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@eDate)+1,0))
)
SELECT DATENAME(MONTH,SDATE) MNAME,SDATE,(CASE WHEN EDATE > @eDate THEN @eDate ELSE EDATE END) EDATE INTO #T FROM CTE_TEST
INSERT INTO T( MNAME,
SDATE,
EDATE)
Select MNAME,
SDATE,
EDATE from #T