IF OBJECT_ID (N'dbo.GetIntervalStartDate', N'FN') IS NOT NULL
DROP FUNCTION dbo.GetIntervalStartDate;
GO
CREATE FUNCTION dbo.GetIntervalStartDate (
@Date datetime
,@IntervalType int = 0
)
RETURNS datetime2
AS
BEGIN
DECLARE @IntervalStartDate datetime;
SELECT @IntervalStartDate =
(case @IntervalType
when 0 then DATEADD(dd,DATEDIFF(dd,0,@Date),0)
when 1 then DATEADD(wk,DATEDIFF(wk,0,@Date),0)
when 2 then DATEADD(mm,DATEDIFF(mm,0,@Date),0)
when 3 then DATEADD(qq,DATEDIFF(qq,0,@Date),0)
when 4 then DATEADD(qq,DATEDIFF(qq,0,@Date),0)
else NULL
end);
RETURN(@IntervalStartDate);
END;
GO