Функция DATEPART стр. 1
Эта функция возвращает целое число, представляющее собой указанную аргументом datepart часть заданной вторым аргументом даты (date).
Список допустимых значений аргумента datepart, описанный выше в данном разделе, дополняется еще одним значением
Заметим, что возвращаемое функцией DATEPART значение в этом случае (номер дня недели) зависит от настроек, которые можно изменить с помощью оператора SET DATEFIRST , устанавливающего первый день недели. Для кого-то понедельник — день тяжелый, а для кого-то — воскресенье. Как и многие региональные настройки, по умолчанию это значение в />Cистема управления реляционными базами данных (СУБД), разработанная корпорацией Microsoft. />Язык структурированных запросов) — универсальный компьютерный язык, применяемый для создания, модификации и управления данными в реляционных базах данных. SQL Server зависит от выбранного языка.
Однако вернемся к примеру 7.1.3. В предположении, что время вылета/прилета является кратным минуте, мы можем его определить как сумму часов и минут. Поскольку функции даты/времени работают с целочисленными значениями, приведем результат к наименьшему интервалу — минутам. Итак, время вылета рейса 1123 в минутах:

Консоль
и время прилета

Консоль
Теперь мы должны сравнить, превышает ли время прилета время вылета. Если это так, следует вычесть из первого второе, чтобы получить продолжительность рейса. В противном случае к разности нужно добавить одни сутки (24*60 = 1440 минут).

Консоль
Здесь, чтобы не повторять длинные конструкции в операторе CASE , использован подзапрос. Конечно, результат получился достаточно громоздким, зато абсолютно корректным в свете сделанных к этой задаче замечаний.
Определить дату и время вылета рейса 1123.
В таблице совершенных рейсов Pass_in_trip содержится только дата рейса, но не время, так как в соответствии с предметной областью каждый рейс может выполняться только один раз в день. Для решения этой задачи нужно к дате, хранящейся в таблице Pass_in_trip, добавить время из таблицы Trip

Консоль
Выполнив запрос, получим следующий результат
DISTINCT необходим здесь, чтобы исключить возможные дубликаты, поскольку номер и дата рейса дублируются в этой таблице для каждого пассажира данного рейса.
В ряде случаев функцию DATEPART можно заменить более простыми функциями. Вот они:
DAY (date) — целочисленное представление дня указанной даты. Эта функция эквивалентна функции DATEPART(dd, date).
MONTH (date) — целочисленное представление месяца указанной даты. Эта функция эквивалентна функции DATEPART(mm, date).
YEAR (date) — целочисленное представление года указанной даты. Эта функция эквивалентна функции DATEPART(yy, date).
Name already in use
sql-docs / docs / t-sql / functions / datepart-transact-sql.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
This function returns an integer representing the specified datepart of the specified date.
See Date and Time Data Types and Functions (Transact-SQL) for an overview of all [!INCLUDEtsql] date and time data types and functions.
. image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false». Transact-SQL syntax conventions
datepart
The specific part of the date argument for which DATEPART will return an integer. This table lists all valid datepart arguments.
[!NOTE] DATEPART does not accept user-defined variable equivalents for the datepart arguments.
| datepart | Abbreviations |
|---|---|
| year | yy, yyyy |
| quarter | qq, q |
| month | mm, m |
| dayofyear | dy, y |
| day | dd, d |
| week | wk, ww |
| weekday | dw |
| hour | hh |
| minute | mi, n |
| second | ss, s |
| millisecond | ms |
| microsecond | mcs |
| nanosecond | ns |
| tzoffset | tz |
| iso_week | isowk, isoww |
date
An expression that resolves to one of the following data types:
- date
- datetime
- datetimeoffset
- datetime2
- smalldatetime
- time
For date, DATEPART will accept a column expression, expression, string literal, or user-defined variable. Use four-digit years to avoid ambiguity issues. See Configure the two digit year cutoff Server Configuration Option for information about two-digit years.
Each datepart and its abbreviations return the same value.
The return value depends on the language environment set by using SET LANGUAGE, and by the Configure the default language Server Configuration Option of the login. The return value depends on SET DATEFORMAT if date is a string literal of some formats. SET DATEFORMAT doesn’t change the return value when the date is a column expression of a date or time data type.
This table lists all datepart arguments, with corresponding return values, for the statement SELECT DATEPART(datepart,’2007-10-30 12:15:32.1234567 +05:10′) . The date argument has a datetimeoffset(7) data type. The last two positions of the nanosecond datepart return value are always 00 and this value has a scale of 9:
.123456700
| datepart | Return value |
|---|---|
| year, yyyy, yy | 2007 |
| quarter, qq, q | 4 |
| month, mm, m | 10 |
| dayofyear, dy, y | 303 |
| day, dd, d | 30 |
| week, wk, ww | 44 |
| weekday, dw | 3 |
| hour, hh | 12 |
| minute, n | 15 |
| second, ss, s | 32 |
| millisecond, ms | 123 |
| microsecond, mcs | 123456 |
| nanosecond, ns | 123456700 |
| tzoffset, tz | 310 |
| iso_week, isowk, isoww | 44 |
Week and weekday datepart arguments
For a week (wk, ww) or weekday (dw) datepart, the DATEPART return value depends on the value set by SET DATEFIRST.
January 1 of any year defines the starting number for the week datepart. For example:
DATEPART (wk, ‘Jan 1, xxxx’) = 1
where xxxx is any year.
This table shows the return value for the week and weekday datepart for ‘2007-04-21 ‘ for each SET DATEFIRST argument. January 1, 2007 falls on a Monday. April 21, 2007 falls on a Saturday. For U.S. English,
SET DATEFIRST 7 — ( Sunday )
serves as the default. After setting DATEFIRST, use this suggested SQL statement for the datepart table values:
SELECT DATEPART(week, ‘2007-04-21 ‘), DATEPART(weekday, ‘2007-04-21 ‘)
year, month, and day datepart Arguments
The values that are returned for DATEPART (year, date), DATEPART (month, date), and DATEPART (day, date) are the same as those returned by the functions YEAR, MONTH, and DAY, respectively.
ISO 8601 includes the ISO week-date system, a numbering system for weeks. Each week is associated with the year in which Thursday occurs. For example, week 1 of 2004 (2004W01) covered Monday, 29 December 2003 to Sunday, 4 January 2004. European countries/regions typically use this style of numbering. Non-European countries/regions typically don’t use it.
Note: the highest week number in a year could be either 52 or 53.
The numbering systems of different countries/regions might not comply with the ISO standard. This table shows six possibilities:
How to get Day or Weekday name from date in Sql Server
Many a times we come across a scenario where we may need to get Day/Weekday name from Date in Sql Server. In this article we will see how we can get Day/Weekday name from Date in Sql Server.
Approach 1: Using DATENAME Function
We can use DATENAME() function to get Day/Weekday name from Date in Sql Server, here we need specify datepart parameter of the DATENAME function as weekday or dw both will return the same result.
RESULT:

Approach 2: Using FORMAT Function
We can aswell use FORMAT function which is introduced in Sql Server 2012 to get Day/Weekday name from Date in Sql Server. It is not an Sql Server native function instead it is .NET CLR dependent function. I would prefer the first approach instead of this approach for getting Day/Weekday name from Date in Sql Server. But FORMAT function provides lot of options compared to DATENAME function. To know more about FORMAT function you may like to go through a detailed article on FORMAT STRING FUNCTION IN SQL SERVER 2012 which I have written couple of years back.

RESULT:
How to get the week day name from a date?
Given 03/09/1982 how can we say it is which week day. In this case it will be Tue .
Is it possible to get in a single query?
![]()
3 Answers 3
(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)
![]()
Nearly ten years late to the party, but I think it’s neccessary to enhance @Zohaib ‘s answer as it’s result depend on the language of the client. If you display the week day name to a user, it’s absolutely fine, but if your code depends on it, I’d rather control the language like so: