sql获取日期区间(年、月、周、日)
通过存储过程获取当前日期(或指定日期)所在的日期区间,包含年、月、周、日。
CREATE PROCEDURE [dbo].[GetDataPeriod] @defaultDate DATE=NULL, @period VARCHAR(1)=NULL, @startDate DATE OUTPUT, @endData DATE OUTPUT AS BEGIN IF @defaultDate IS NULL BEGIN SET @defaultDate=GETDATE(); END IF @period IS NULL BEGIN SET @period='M'; END --第一天 SELECT @startDate= CASE @period WHEN 'Y' THEN DATEADD(YEAR, DATEDIFF(YEAR,0,@defaultDate), 0) WHEN 'M' THEN DATEADD(MONTH, DATEDIFF(MONTH,0,@defaultDate), 0) WHEN 'W' THEN DATEADD(WEEK, DATEDIFF(WEEK,0,@defaultDate), 0) WHEN 'D' THEN DATEADD(DAY, DATEDIFF(DAY,0,@defaultDate), 0) END; IF @defaultDate<@startDate BEGIN SET @defaultDate=DATEADD(DAY,-1,@defaultDate); EXEC dbo.Report_GetPeriod @defaultDate,@period,@startDate OUTPUT,@endData OUTPUT; END ELSE BEGIN --最后一天 SELECT @endData= CASE @period WHEN 'Y' THEN DATEADD(DAY,-1,DATEADD(YEAR,1,DATEADD(YEAR, DATEDIFF(YEAR,0,@defaultDate), 0))) WHEN 'M' THEN DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(MONTH, DATEDIFF(MONTH,0,@defaultDate), 0))) WHEN 'W' THEN DATEADD(DAY,-1,DATEADD(WEEK,1,DATEADD(WEEK, DATEDIFF(WEEK,0,@defaultDate), 0))) WHEN 'D' THEN DATEADD(DAY, DATEDIFF(DAY,0,@defaultDate), 0) END; END END
使用实例
DECLARE @startDate DATE, @endData DATE; EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20', @period = 'Y', @startDate = @startDate OUTPUT, @endData = @endData OUTPUT SELECT @startDate,@endData;--// 2017-01-01 2017-12-31 EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20', @period = 'M', @startDate = @startDate OUTPUT, @endData = @endData OUTPUT SELECT @startDate,@endData;--// 2017-06-01 2017-06-30 EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20', @period = 'W', @startDate = @startDate OUTPUT, @endData = @endData OUTPUT SELECT @startDate,@endData;--// 2017-06-19 2017-06-25 EXEC dbo.GetDataPeriod @defaultDate = '2017-06-20', @period = 'D', @startDate = @startDate OUTPUT, @endData = @endData OUTPUT SELECT @startDate,@endData;--// 2017-06-20 2017-06-20
相关推荐
xuanlvhaoshao 2020-05-07
militala 2020-01-13
cjylean 2019-12-04
tanrong 2020-01-14
Carlos 2020-01-08
明月清风精进不止 2020-01-01
tanrong 2019-12-13
明月清风精进不止 2019-10-23
zhangdonghang 2019-07-18
chenxcd 2019-09-06
sylalak 2014-08-30
FightFourEggs 2010-08-14
廖金龙 2013-03-20
wangcomputer00 2012-07-06
windex000 2018-10-15
libingjy 2016-10-05
MikeG 2015-07-26