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>
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>
Important Notes
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!