рефакторинг xp.Сделал исходя из предположения
что практически всегда период = Месяц
для _1sp_GetBeginOfPeriod М поставил первым в IF
Create procedure _1sp_GetNextPeriod(@BaseDate DATETIME, @Period CHAR(1), @NewDate DATETIME OUTPUT) AS
SET NOCOUNT ON
SET DATEFIRST 1
DECLARE @BeginOfPeriod datetime
DECLARE @day integer
IF @Period='M' BEGIN
SELECT @NewDate = DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BaseDate), '1753-02-01')
RETURN
END
EXECUTE _1sp_GetBeginOfPeriod @BaseDate, @Period, @BeginOfPeriod OUTPUT
IF @Period='D'
SELECT @NewDate=DATEADD(dd, 1, @BeginOfPeriod)
ELSE IF @Period='W'
SELECT @NewDate=DATEADD(wk, 1, @BeginOfPeriod)
ELSE IF @Period='M'
SELECT @NewDate=DATEADD(mm, 1, @BeginOfPeriod)
ELSE IF @Period='Q'
SELECT @NewDate=DATEADD(qq, 1, @BeginOfPeriod)
ELSE IF @Period='Y'
SELECT @NewDate=DATEADD(yy, 1, @BeginOfPeriod)
ELSE IF @Period='T' BEGIN
SELECT @day=DATEPART(dd, @BeginOfPeriod)
IF @day>15 SELECT @NewDate=DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BeginOfPeriod), '1753-02-01')
ELSE SELECT @NewDate=DATEADD(dd, 15, @BeginOfPeriod)
END
ELSE IF @Period='C' BEGIN
SELECT @day=DATEPART(dd, @BeginOfPeriod)
IF @day>20 SELECT @NewDate=DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BeginOfPeriod), '1753-02-01')
ELSE SELECT @NewDate=DATEADD(dd, 10, @BeginOfPeriod)
END
ELSE IF @Period='F' BEGIN
SELECT @day=DATEPART(dd, @BeginOfPeriod)
IF @day>25 SELECT @NewDate=DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BeginOfPeriod), '1753-02-01')
ELSE SELECT @NewDate=DATEADD(dd, 5, @BeginOfPeriod)
END
ELSE SELECT @NewDate=CONVERT(datetime, '1753-01-01')
GO
Create procedure _1sp_GetBeginOfPeriod(@BaseDate DATETIME, @Period CHAR(1), @NewDate DATETIME OUTPUT) AS
SET NOCOUNT ON
SET DATEFIRST 1
DECLARE @Day int
IF @Period='M'
SELECT @NewDate=DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BaseDate), '1753-01-01')
ELSE IF @Period='D'
SELECT @NewDate=@BaseDate
ELSE IF @Period='W'
SELECT @NewDate=DATEADD(dd, -DATEPART(dw, @BaseDate)+1, @BaseDate)
ELSE IF @Period='Q'
SELECT @NewDate=DATEADD(qq, DATEDIFF(qq, '1753-01-01', @BaseDate), '1753-01-01')
ELSE IF @Period='Y'
SELECT @NewDate=DATEADD(yy, DATEDIFF(yy, '1753-01-01', @BaseDate), '1753-01-01')
ELSE IF @Period='T'
BEGIN
SELECT @Day=DATEPART(dd, @BaseDate )
IF @Day>15 SELECT @Day=15
ELSE SELECT @Day=0
SELECT @NewDate=DATEADD(dd, @Day, DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BaseDate), '1753-01-01'))
END
ELSE IF @Period='C'
BEGIN
SELECT @Day=DATEPART(dd, @BaseDate )
IF @Day>20 SELECT @Day=20
ELSE IF @Day>10 SELECT @Day=10
ELSE SELECT @Day=0
SELECT @NewDate=DATEADD(dd, @Day, DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BaseDate), '1753-01-01'))
END
ELSE IF @Period='F'
BEGIN
SELECT @Day=DATEPART(dd, @BaseDate )
IF @Day>25 SELECT @Day=25
ELSE IF @Day>20 SELECT @Day=20
ELSE IF @Day>15 SELECT @Day=15
ELSE IF @Day>10 SELECT @Day=10
ELSE IF @Day>5 SELECT @Day=5
ELSE SELECT @Day=0
SELECT @NewDate=DATEADD(dd, @Day, DATEADD(mm, DATEDIFF(mm, '1753-01-01', @BaseDate), '1753-01-01'))
END
ELSE SELECT @NewDate=CONVERT(datetime, '1753-01-01')
GO