A horrible situation....Say you are using a shared server and apps can get moved around to different servers based on loads and for some reason one server was setup with a different firstDate for another application....and you are returning the week day in a table function (ie can't set firstdate in this function). This will always guarantee 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