SQL Server DATEPART() 取出日期和時間中特定的部分
在 SQL Server 中,我們可以用 DATEPART() 函數來取出日期和時間中特定的部分,比如年、月、日、時、分、秒等。
DATEPART() 語法 (Syntax)
DATEPART(datepart , date)
DATEPART() 會返回一個整數,其中 datepart 參數用來指定要返回的部分,datepart 可以是這些值:
| datepart (全名和縮寫) | 返回值說明 |
|---|---|
| year, yyyy, yy | 年,例如 2007 |
| month, mm, m | 月,例如 10 |
| day, dd, d | 日,例如 30 |
| hour, hh | 時,例如 12 |
| minute, n | 分,例如 15 |
| second, ss, s | 秒,例如 32 |
| millisecond, ms | 毫秒,例如 123 |
| microsecond, mcs | 微秒,例如 123456 |
| nanosecond, ns | 毫微秒,例如 123456700 |
| quarter, qq, q | 季,例如 4 |
| dayofyear, dy, y | 一年中的第幾天,例如 303 |
| week, wk, ww | 一年中的第幾週,例如 45 |
| weekday, dw | 星期幾,例如 1 |
| TZoffset, tz | 時區 time zone offset,單位是分鐘,例如 310 |
DATEPART() 用法 (Example)
假設有一個 Orders table:
| OrderId | ProductName | OrderDate |
|---|---|---|
| 1 | 'Bike' | 2018-10-22 16:25:46.635 |
這個 SQL:
SELECT DATEPART(yyyy, OrderDate) AS OrderYear,
DATEPART(mm, OrderDate) AS OrderMonth,
DATEPART(dd, OrderDate) AS OrderDay
FROM Orders
會得到例如:
| OrderYear | OrderMonth | OrderDay |
|---|---|---|
| 2018 | 10 | 22 |