Explain Codes LogoExplain Codes Logo

Get week day name from a given month, day, and year individually in SQL Server

sql
date-parsing
sql-server
date-functions
Nikita BarsukovbyNikita Barsukov·Oct 17, 2024
TLDR

To get the weekday name from separate year, month, and day components in SQL Server, make use of the DATENAME and DATEFROMPARTS functions:

SELECT DATENAME(weekday, DATEFROMPARTS(2023, 3, 14)) as WeekdayName -- Result: "Tuesday"

Here, DATENAME retrieves the name of the date part you specify from the given date. DATEFROMPARTS generates a valid date from its year, month, and day parameters.

Exploring Different Methods

With SQL Server, you can extract the weekday name in several ways, especially depending on the server version and broader context at hand. We also can mix DATEPART with DATENAME or even engage the CONVERT function for advanced date parsing before using DATENAME to extract the name of the weekday.

How to Tackle Various Scenarios

Adapting for Different SQL Server Versions

Not every version of SQL Server treats dates in the same way. DATEFROMPARTS works smoothly for versions 2012 and onwards but for older siblings such as 2005 and 2008 versions, you'll need to do a little detour and use CAST or CONVERT:

-- For SQL Server 2008 and earlier: SELECT DATENAME(weekday, CAST(CONCAT('2023', '-', '03', '-', '14') AS datetime)) AS WeekdayName -- Again hope for "Tuesday"

Dealing with Date Formatting Issues

It's paramount to have the date in the correct format or risk having angry red errors yelling at you in your console. So, lets use CONVERT with a style code to ensure the format is right even when the date does not look zen:

SELECT DATENAME(weekday, CONVERT(datetime, '03/14/2023', 101)) AS WeekdayName -- Guess what we expect? Yup, "Tuesday"!

Handling Errors and Exceptions

Dealing with invalid dates or data type mismatches is part of the package sometimes. We can handle these like old pros by using error-checking with TRY_CONVERT and TRY_CAST methods:

SELECT DATENAME(weekday, TRY_CONVERT(datetime, CONCAT(month, '/', day, '/', year), 101)) AS WeekdayName -- It's Tuesday again, isn't it?

Verifying Your Results

Always check your workings—consistent accuracy matters! Test with different input dates and leap years, and handle regional date formats carefully.

Optimal Practices for Performance and Accuracy

Conciseness and readability aren't just good for you, but also for whoever has to maintain your code. Always opt for built-in date functions over manual string manipulation—there's less room for time-zone or format errors, and no one likes inconsistencies.

Never skip testing the solution in different SQL Server versions for forward compatibility. It's good practice to check your SQL syntax against the specific SQL Server version to ensure the code is not using deprecated features—your future self will thank you.