我正在使用SQLServer 2008开发一个财务应用程序作为数据库,我希望生成任何一年的财政期间,例如
输入:2010年6月
结果需要从2010年6月 - 2011年5月开始的12个时期
周期...............。开始.............................. .... ......... ..End 1 ... ... .................. 2010年1月6日................................. 30-06-2010 2 .......... 2010年1月7日........... 31-07-2010
依此类推,直到2010年5月......实际上需要从任何月份开始获得12行(12个月),输出将是该月的开始日期,结束将是该月的最后一天,例如在我的场景中2010年6月 - 2011年5月..这将是什么问题。
先谢谢
答案 0 :(得分:1)
请参阅DATEADD()
select convert(datetime,'6/1/2010')
select DATEADD(day,-1,DATEADD(month,1,convert(datetime,'6/1/2010'))) --6/30/2010
select DATEADD(month,1,convert(datetime,'6/1/2010')) --7/1/2010
你可能会在一个存储过程中运行它,这会生成一个临时表,或者只是一个大查询快速而且非常脏......
我毫不犹豫地为你做了整件事,但干草是什么......
create procedure getFiscalYear
@startDate nvarchar(10)
as begin
declare @myDate datetime
set @myDate = convert(datetime,@startDate)
select 1 as Period, @myDate as startDate, DATEADD(day,-1,DATEADD(month,1,@myDate)) as endDate
union
select 2 as Period, DATEADD(month,1,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,2,@myDate)) as endDate
union
select 3 as Period, DATEADD(month,2,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,3,@myDate)) as endDate
union
select 4 as Period, DATEADD(month,3,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,4,@myDate)) as endDate
union
select 5 as Period, DATEADD(month,4,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,5,@myDate)) as endDate
union
select 6 as Period, DATEADD(month,5,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,6,@myDate)) as endDate
union
select 7 as Period, DATEADD(month,6,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,7,@myDate)) as endDate
union
select 8 as Period, DATEADD(month,7,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,8,@myDate)) as endDate
union
select 9 as Period, DATEADD(month,8,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,9,@myDate)) as endDate
union
select 10 as Period, DATEADD(month,9,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,10,@myDate)) as endDate
union
select 11 as Period, DATEADD(month,10,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,11,@myDate)) as endDate
union
select 12 as Period, DATEADD(month,11,@myDate) as startDate, DATEADD(day,-1,DATEADD(month,12,@myDate)) as endDate
end
这是丑陋的方式......
答案 1 :(得分:1)
这是使用公用表表达式创建句点列表的方法。我借用@Fosco的DATEADD方法(thx @Fosco)。
DECLARE @StartDate DATETIME = '06/1/2010';
WITH periods AS
(SELECT 1 AS period
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9
UNION SELECT 10
UNION SELECT 11
UNION SELECT 12
)
SELECT period,
DATEADD(month,period-1,@StartDate) as startDate,
DATEADD(day,-1,DATEADD(month,period,@StartDate)) as endDate
FROM periods
有多种方法可以创建您的期间列表。有关示例,请参阅this。