Да, ваша логика верна.Используйте оператор case
вместе с некоторыми функциями DATE
в SQL SERVER.С моим ограниченным знанием функций даты SQL SERVER я сформулировал следующий запрос.Вы все еще можете оптимизировать это.
SELECT
RUN_DATE,SCHEDULE,
case
when (DATEPART(month,run_date)=month(sysdatetime()) --checking same month
and DATEPART(day, run_date) between 2 and 15 and Schedule='15th') --checking date between 2nd and 15th and schedule is 15th
then DATEADD(month, DATEDIFF(month, 0,run_date), 0)+14 --selecting 15th of same month
when (DATEPART(month,run_date)=month(sysdatetime())
and DATEPART(day, run_date) between 2 and 15 and Schedule='1st') --checking date between 2nd and 15th and schedule is 1st
then DATEADD(month, DATEDIFF(month, 0,run_date)+1, 0) --selecting 1st of next month
when (DATEPART(month,run_date)=month(sysdatetime()) or run_date=DATEADD(month, DATEDIFF(month, 0,run_date)+1,0))
and (((DATEPART(day, run_date) between 16 and 31) or (run_date=DATEADD(month, DATEDIFF(month, 0,run_date)+1,0)))
and Schedule='1st')
then case when (run_date=DATEADD(month, DATEDIFF(month, 0,run_date),0))
then
DATEADD(month, DATEDIFF(month, 0,run_date),0) -- if 1st of next month, select first day of same month
else
DATEADD(month, DATEDIFF(month, 0,run_date)+1,0) --selecting 1st of next month
end
when (DATEPART(month,run_date)=month(sysdatetime()) or run_date=DATEADD(month, DATEDIFF(month, 0,run_date),0))
and (((DATEPART(day, run_date) between 16 and 31) or (run_date=DATEADD(month, DATEDIFF(month, 0,run_date),0)))
and Schedule='15th')
then case when (run_date=DATEADD(month, DATEDIFF(month, 0,run_date),0))
then
DATEADD(month, DATEDIFF(month, 0,run_date),0)+14 -- if 1st of next month, select 15 of same month
else
DATEADD(month, DATEDIFF(month, 0,run_date)+1,0)+14 --selecting 15th of next month
end
end as NEXT_BILL_RUN_DATE
FROM mytable ;