A terrible situation .... Suppose you use a shared server, and applications can move to other servers depending on the load, and for some reason one server was configured with another firstDate for another application .... and you return the day of the week in a table function (that is, it cannot set the first date in this function). This always guarantees Monday as the first day.
CREATE FUNCTION fnGetMondayWD(@WD INT) RETURNS INT AS BEGIN /* think of 1 to 7 as a clock that can rotate forwards or backwards */ DECLARE @OFFSET INT, @calc INT; SET @offset = @@DATEFIRST + @WD - 1;--Monday DateFirst SET @calc = IIF(@offset > 7, @offset - 7, @offset); -- could be @offset % 7 (less readable more efficient) RETURN @calc; END; go -- Test Cases SET datefirst 7 select dbo.fnGetMondayWD(2) Mon, dbo.fnGetMondayWD(3)Tue, dbo.fnGetMondayWD(4)Wed, dbo.fnGetMondayWD(5)Thur, dbo.fnGetMondayWD(6)Fri, dbo.fnGetMondayWD(7)Sat, dbo.fnGetMondayWD(1)Sun SET datefirst 6 select dbo.fnGetMondayWD(3) Mon, dbo.fnGetMondayWD(4)Tue, dbo.fnGetMondayWD(5)Wed, dbo.fnGetMondayWD(6)Thur, dbo.fnGetMondayWD(7)Fri, dbo.fnGetMondayWD(1)Sat, dbo.fnGetMondayWD(2)Sun SET datefirst 5 select dbo.fnGetMondayWD(4) Mon, dbo.fnGetMondayWD(5)Tue, dbo.fnGetMondayWD(6)Wed, dbo.fnGetMondayWD(7)Thur, dbo.fnGetMondayWD(1)Fri, dbo.fnGetMondayWD(2)Sat, dbo.fnGetMondayWD(3)Sun SET datefirst 1 select dbo.fnGetMondayWD(1) Mon, dbo.fnGetMondayWD(2)Tue, dbo.fnGetMondayWD(3)Wed, dbo.fnGetMondayWD(4)Thur, dbo.fnGetMondayWD(5)Fri, dbo.fnGetMondayWD(6)Sat, dbo.fnGetMondayWD(7)Sun
source share