I am trying get a day name like friday, saturday, sunday, monday etc from a given date. I know there is a built in function which returns the day name for example:
SELECT DATENAME(dw,'09/23/2013') as theDayName
this SQL query returns:
'Monday'
This is all OK. But I would like to pass Month, Day and Year
individually.
I am using the builtin DATEPART function to retrieve month, day and year from a date so I can pass it to the DATENAME function:
SELECT DATEPART(m, GETDATE()) as theMonth -- returns 11 SELECT DATEPART(d, GETDATE()) as theDay -- returns 20 SELECT DATEPART(yy, GETDATE()) as theYear -- returns 2013
Now that I have Month, Day, Year values individually, I pass it to my DATENAME
to get the Weekname
of the date I want:
--my SQL query to return dayName SELECT (DATENAME(dw, DATEPART(m, GETDATE())/DATEPART(d, myDateCol1)/ DATEPART(yy, getdate()))) as myNameOfDay, FirstName, LastName FROM myTable
This returns an incorrect Day Name. I tried replace / with - so that in the DATENAME function my SQL query becomes:
SELECT DATENAME(dw,'09/23/2013') --becomes SELECT DATENAME(dw,'09-23-2013')
but it still returns incorrect dayName from my SQL query. Am I missing something here.
Please advise.
Method 1: DateName() Function for Day Name This is one of the most popular methods. DECLARE @DateVal DATE = '2020-07-27'; SELECT @DateVal As [Date], DATENAME(WEEKDAY, @DateVal) AS [Day Name]; When you run the above script you will see the date which is passed along with the day name.
If you want to get a day from a date in a table, use the SQL Server DAY() function. This function takes only one argument – the date. This can be a date or date and time data type. (In our example, the column VisitDate is of the date data type.)
The DATENAME() function returns the date part as a character string whereas the DATEPART() returns the date part as an integer.
Tested and works on SQL 2005 and 2008. Not sure if this works in 2012 and later.
The solution uses DATENAME instead of DATEPART
select datename(dw,getdate()) --Thursday select datepart(dw,getdate()) --2
This is work in sql 2014 also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With