What is the function of the dateadd function in SQL Ser…
The DATEADD function in SQL Server is used to add or subtract a specified time interval to a given date. It functions by increasing or decreasing a specified date by a certain amount based on a specified unit (such as year, month, day, hour, minute, etc.).
The syntax of the DATEADD function is as follows:
DATEADD (datepart, number, date)
The datepart parameter specifies the unit of time to add or subtract, and can be one of the following values:
- year
- quarter: a period of three months
- month: a unit of time that is approximately four weeks long, usually containing 30 or 31 days.
- Number of days in a year
- day: sun
- week: seven days
- Number of days within a week.
- hour: a unit of time equal to 60 minutes
- minute: a unit of time equal to 60 seconds
- second: a unit of time equal to 1/60th of a minute
- millisecond: a unit of time equal to one thousandth of a second
- microsecond means a very short period of time
- nanosecond: a unit of time equal to one billionth of a second
The number parameter specifies the quantity to be added or subtracted, which can be positive (towards the future) or negative (towards the past).
The date parameter is a date or time value that represents the reference date for the operation.
The DATEADD function returns a new date value that is the result of adding or subtracting a specified time interval to a given date.
Here are some examples of using the DATEADD function:
-- 在当前日期上增加一个月
SELECT DATEADD(month, 1, GETDATE())
-- 在指定日期上减去一个小时
SELECT DATEADD(hour, -1, '2022-01-01 10:30:00')
-- 在指定日期上增加两周
SELECT DATEADD(week, 2, '2022-01-01')
-- 在指定日期上增加 30 分钟
SELECT DATEADD(minute, 30, '2022-01-01 10:00:00')
Using the DATEADD function makes it easy to perform calculations and manipulate dates and times.