摘要:在本教程中,您將學習如何使用 SQL DATEPART() 函式從給定日期中返回日期的指定部分,例如年、月和日。
請注意,DATEPART() 函式不屬於 SQL 標準,只有 SQL Server 支援它。
SQL DATEPART 函式簡介 #
DATEPART() 函式返回一個整數值,該值表示給定日期的指定部分,例如年、月和日。
以下是 DATEPART() 函式的語法:
DATEPART(datepart, date)Code language: SQL (Structured Query Language) (sql)在此語法中:
datepart是您想要提取日期元件的單位,例如年、月、日、小時、分鐘和秒。詳情請參見下表。date是您想要從中提取元件的日期、時間、時間戳等。
DATEPART() 函式返回一個整數值,其單位由 datepart 引數指定。
下表顯示了 datepart 的有效值:
| datepart |
|---|
| 年: year, yyyy, yy |
| 季度: quarter, qq, q |
| 月: month, mm, m |
| 年中的日: dayofyear, dy, y |
| 日: day, dd, d |
| 周: week, wk, ww |
| 星期: weekday, dw |
| 小時: hour, hh |
| 分鐘: minute, n |
| 秒: second, ss, s |
| 毫秒: millisecond, ms |
| 微秒: microsecond, mcs |
| 納秒: nanosecond, ns |
| 時區偏移: TZoffset, tz |
SQL DATEPART 函式示例 #
讓我們來看一些使用 DATEPART 函式的例子。
基本的 DATEPART 函式示例 #
以下查詢使用 DATEPART 函式提取日期的各個部分:
SELECT
DATEPART(year, '2018-07-21 15:30:20.05') y,
DATEPART(quarter, '2018-07-21 15:30:20.05') q,
DATEPART(month, '2018-07-21 15:30:20.05') m,
DATEPART(dayofyear, '2018-07-21 15:30:20.05') d,
DATEPART(week, '2018-07-21 15:30:20.05') w,
DATEPART(hour, '2018-07-21 15:30:20.05') h,
DATEPART(minute, '2018-07-21 15:30:20.05') m,
DATEPART(second, '2018-07-21 15:30:20.05') s;Code language: SQL (Structured Query Language) (sql)此演練場支援一個名為 DATE_PART 的類似函式。因此,您將看到一個略有不同的語句。
輸出
y | q | m | d | w | h | m | s
------+---+---+----+----+----+----+-------
2018 | 3 | 7 | 21 | 29 | 15 | 30 | 20.05Code language: plaintext (plaintext)在表資料中使用 DATEPART 函式 #
以下語句使用 DATEPART 函式查詢在 1999 年加入公司的員工:
SELECT
first_name,
last_name,
hire_date
FROM
employees
WHERE
DATEPART(YEAR, hire_date) = 1999;Code language: SQL (Structured Query Language) (sql)輸出
first_name | last_name | hire_date
------------+------------+------------
Diana | Lorentz | 1999-02-07
Luis | Popp | 1999-12-07
Karen | Colmenares | 1999-08-10
Kimberely | Grant | 1999-05-24Code language: plaintext (plaintext)摘要 #
- 使用 SQL
DATEPART()函式從給定日期中提取日期的一部分。
本教程是否有幫助?