EnVisageOnline/Main/Database/Scripts/20160323/03_GetTeamEndDateWe_Create.sql

46 lines
911 B
Transact-SQL

Use [EnVisage]
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[GetFCWeekEndForDate]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
DROP FUNCTION [dbo].[GetFCWeekEndForDate]
GO
CREATE FUNCTION GetFCWeekEndForDate (@dt date)
RETURNS date
AS
BEGIN
DECLARE @ret date
DECLARE @maxDate date
DECLARE @weekStart date
DECLARE @weekEnd date
if (@dt is null)
return null
select @maxDate = MAX(EndDate) from FiscalCalendar
where ([Type] = 0)
if (@dt >= @maxDate)
set @ret = null
else
begin
select top 1 @weekStart = StartDate, @weekEnd = EndDate from FiscalCalendar
where ([Type] = 0) and (StartDate <= @dt) and (EndDate >= @dt)
if (@weekStart is null)
set @ret = @dt
else
begin
if (@dt = @weekEnd)
set @ret = @weekEnd
else
set @ret = DATEADD(day, -1, @weekStart)
end
end
RETURN @ret
END
GO