I have a Query where I get the WeekDay of a date but by default:
Sunday = 1
Moday = 2
etc.
I think this could work:
select
case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
I think
DATEPART(dw,ads.date - 1) as weekday
would work.
I would suggest that you just write the case statement yourself using datename()
:
select (case datename(dw, aws.date)
when 'Monday' then 1
when 'Tuesday' then 2
when 'Wednesday' then 3
when 'Thursday' then 4
when 'Friday' then 5
when 'Saturday' then 6
when 'Sunday' then 7
end)
At least, this won't change if someone changes the parameter on the day of the week when weeks begin. On the other hand, it is susceptible to the language chosen for SQL Server.
Try this:
CREATE FUNCTION dbo.FnDAYSADDNOWK(
@addDate AS DATE,
@numDays AS INT
) RETURNS DATETIME AS
BEGIN
WHILE @numDays > 0 BEGIN
SET @addDate = DATEADD(day, 1, @addDate)
IF DATENAME(DW, @addDate) <> 'sunday' BEGIN
SET @numDays = @numDays - 1
END
END
RETURN CAST(@addDate AS DATETIME)
END
This will do it.
SET DATEFIRST 1;
-- YOUR QUERY
Examples
-- Sunday is first day of week
set datefirst 7;
select DATEPART(dw,getdate()) as weekday
-- Monday is first day of week
set datefirst 1;
select DATEPART(dw,getdate()) as weekday
You would need to set DATEFIRST. Take a look at this article. I believe this should help.
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql