AhDung

/*追求代码质量的野生码农*/

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

注:周节点是根据中国习惯,视周一为起,周日为末。 

/*---------------------------------
函数:获取某日期的特定起止日期v0.02
Author:AhDung
Update:201607251729。无论@@datefirst为何值,均不影响周节点
---------------------------------*/
ALTER FUNCTION dbo.FGetSpecialDate_ahdung(@date DATE, @SpcDate VARCHAR(20))
RETURNS DATE AS
BEGIN
IF @date IS    NULL RETURN NULL
IF @SpcDate IN ('YearBeg','YB','NC','年初') RETURN DATENAME(YEAR,@date)+'-01-01'
ELSE IF @SpcDate IN ('YearEnd','YE','NW','年尾','年末') RETURN DATENAME(YEAR,@date)+'-12-31'
ELSE IF @SpcDate IN ('QuarterBeg','QtBeg','QB','JC','季初') RETURN DATENAME(YEAR,@date)+CASE WHEN MONTH(@date)<=3 THEN '-01' WHEN MONTH(@date)<=6 THEN '-04' WHEN MONTH(@date)<=9 THEN '-07' ELSE '-10' END +'-01'
ELSE IF @SpcDate IN ('QuarterEnd','QtEnd','QE','JW','季尾','季末') RETURN DATENAME(YEAR,@date)+CASE WHEN MONTH(@date)<=3 THEN '-03-31' WHEN MONTH(@date)<=6 THEN '-06-30' WHEN MONTH(@date)<=9 THEN '-09-30' ELSE '-12-31' END
ELSE IF @SpcDate IN ('MonBeg','MB','YC','月初') RETURN CONVERT(CHAR(7),@date,120)+'-01'
ELSE IF @SpcDate IN ('MonEnd','ME','YW','月尾','月末') RETURN DATEADD(DAY,-1,CONVERT(CHAR(7),DATEADD(MONTH,1,@date),120)+'-01')
ELSE IF @SpcDate IN ('WeekBeg','WB','ZY','周一','WeekEnd','WE','ZR','ZM','周日','周末')
BEGIN
DECLARE @dw INT=DATEPART(dw,@date)
DECLARE @diff INT = 9-@@DATEFIRST
DECLARE @d INT= CASE WHEN @dw<@diff THEN @dw+7 ELSE @dw END
IF @SpcDate IN ('WeekBeg','WB','ZY','周一') RETURN DATEADD(DAY,@diff-@d,@date)
RETURN DATEADD(DAY,@diff-@d+6,@date)
END
RETURN @date
END
posted on 2013-05-16 11:00  ahdung  阅读(744)  评论(0编辑  收藏  举报