System functions in SQL Server are very useful objects and can help us implement many Algorithm Function. The following is a summary of the built-in functions for system time:
1
. Dateadd:
Usage: dateadd (timeinterval, number, date) adds the number * timeinterval time difference to the date value.
Timeinterval-interval time unit, such as day or DD (day), mm (month), HH (hour), ww (week), YY (year), S (second)
Number ----- number of times of the interval (positive or negative. You can obtain the future time or the past time)
Date -------- reference time
Eg: dateadd (HH, 10, getdate () takes 10 hours after the system time
Dateadd (day,-3, getdate () is the three days before the system time.
2. datediff:
Usage: datediff (timeinterval, date1, date2) calculates the time difference from date1 to date2. The returned value is in the unit of timeinterval. date1 returns a negative value after date2.
Eg: datediff (day, '2014-9-1 ', getdate () returns the number of days from 2009-9-1 to the system time (day)
Datediff (HH, getdate (), '2017-9-1 ') returns the hour from the system time to 2009-9-1 (HH)
3. datename : Return some information in the time and date string (such as year, month ,)
Usage: datename (datepart, date)
Datepart:Yes
Date. The following table lists all valid
DatepartParameters. The user-defined equivalent variable is invalid.
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 |
Date; allows expressions, column expressions, User-Defined variables, or string characters. (Original msdn)
example: returns the information about the current system time, such as middle-aged, month, day, dayofyear, and week.
select datename (year, getdate ()
, datename (month, getdate ()
, datename (day, getdate ()
, datename (dayofyear, getdate ()
, datename (weekday, getdate ();
result: 2009 09 2 245 Wednesday
4. datepart
usage: datepart (datepart, date) works similarly to datename.
the difference between the two is shown in the following example: datename returns the string type, datepart returns the int type
select datepart (year, getdate ()
, datepart (month, getdate ()
, datepart (day, getdate ()
, datepart (dayofyear, getdate ()
, datepart (weekday, getdate ();
result: 2009 9 2 245 4