Home > Database > Mysql Tutorial > How to Get the Day of the Week in SQL Server using DATENAME and DATEPART?

How to Get the Day of the Week in SQL Server using DATENAME and DATEPART?

Patricia Arquette
Release: 2025-01-12 08:02:42
Original
568 people have browsed it

How to Get the Day of the Week in SQL Server using DATENAME and DATEPART?

Extracting the Day of the Week in SQL Server (2005/2008 and later)

A frequent requirement in SQL Server database management involves identifying the weekday corresponding to a given date. This functionality proves invaluable for tasks like scheduling or analyzing data based on the day of the week.

Leveraging Built-in Functions

SQL Server offers two native functions for this purpose: DATENAME and DATEPART.

Employing DATENAME

The DATENAME function yields a text string representing a specified date component. To obtain the weekday, use the 'dw' format specifier:

<code class="language-sql">SELECT DATENAME(dw, '20090101') -- Returns 'Thursday'</code>
Copy after login

Utilizing DATEPART

The DATEPART function returns a numerical value representing the specified date component. 'dw' signifies the day of the week (1 for Sunday, 7 for Saturday):

<code class="language-sql">SELECT DATEPART(dw, '20090101') -- Returns 5 (Thursday)</code>
Copy after login

Important Notes

  • The examples above use a date string. You can substitute a date variable or expression.
  • The returned weekday reflects the default language and date format settings of your SQL Server instance.
  • For weekday retrieval in a different language, use the SET LANGUAGE statement to adjust the language setting.

The above is the detailed content of How to Get the Day of the Week in SQL Server using DATENAME and DATEPART?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template