如何在 sql 服务器中获取两个日期之间的开始日期和结束日期
How to get start date and end date between two dates in sql server
大家好,我正在研究某种会计系统,遇到了一些困难。该问题已由 Abdul Rasheed 在此站点中回答。
这是代码
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
代码工作得很好,就像我想要的一样。但我想将结果插入一个新的 table。我该怎么做?
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
大家好,我正在研究某种会计系统,遇到了一些困难。该问题已由 Abdul Rasheed 在此站点中回答。
这是代码
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
代码工作得很好,就像我想要的一样。但我想将结果插入一个新的 table。我该怎么做?
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