I have written article about SQL SERVER – UDF – Get the Day of the Week Function. I have received good modified script from reader Mihir Popat has suggested another code where Sunday does not have to be necessary the first day of the week.
CREATE FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @rtDayofWeek VARCHAR(10)
DECLARE @weekDay INT
-- Here I have subtracted 7 For keeping Sunday as the First day
-- like wise for Monday we need to subtract 2 and so on
SET @weekDay = ((DATEPART(dw,GETDATE())+@@DATEFIRST-7)%7)
SELECT @rtDayofWeek = CASE @weekDay
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
RETURN (@rtDayofWeek)
END
GO
SELECT dbo.udf_DayOfWeek(GETDATE())
Reference : Pinal Dave (http://blog.SQLAuthority.com), Mihir Popat




I’m still a little confused as to why you would want to go through the trouble of calling a UDF with 18 to 20 lines of code when the SQL Server development team has already done it for you.
SELECT DATENAME(dw, GETDATE())
I do understand the fun that can be had with trying to solve complex problems with T-SQL, but this is not one of those complex problems. It’s built in to the system for anyone to use when ever they want.
Hi Pinal,
I’m also surprised to see effort you’ve put to retrive Day of week for a given date. DATENAME function can perform this task pretty well.
I’m sure you must be aware of this function but you might have face some issue with it. Could you please share those issues wit DATENAME function?
Thanks & Regards,
Sudev Gandhi
[http://sudev.blogspot.com
Hi Pinal,
Actually the function u posted is returning ‘NULL’ for Saturdays and works for rest all days. And you didn’t use the given argument inside the funciton instead you used getdate(). this also returns error. The following is working…
Create FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @rtDayofWeek VARCHAR(10)
DECLARE @weekDay INT
–Here I have subtracted 7 For keeping Sunday as the First day like wise for Monday we need to subtract 2 and so on
set @weekDay=((DATEPART(dw,@dtDate)+@@DATEFIRST-7)%7)
SELECT @rtDayofWeek = CASE @weekDay
WHEN 1 THEN ‘Sunday’
WHEN 2 THEN ‘Monday’
WHEN 3 THEN ‘Tuesday’
WHEN 4 THEN ‘Wednesday’
WHEN 5 THEN ‘Thursday’
WHEN 6 THEN ‘Friday’
WHEN 0 THEN ‘Saturday’
END
RETURN (@rtDayofWeek)
END
GO
select dbo.udf_dayofweek(getdate())
I’m happy to reply this post as Novice DBA
Nandha
[...] 27, 2008 by pinaldave Datetime functions and stored procedures always interests me. Nanda Kumar has suggested modification to previous written article about SQL SERVER – SQL SERVER – UDF – Get [...]
Thanks a lot for this – right on the button and saved me a deal of work.
Great stuff
Ray
Sydney
Australia
is this work with sql 2000
Thanks Pinal :)