sql dateadd函数

This article explores the DATEADD SQL function and its usage scenarios with various examples.

本文通过各种示例探索DATEADD SQL函数及其使用方案。

Usually, we work with date data type in SQL Server. We need to do manipulations with dates as well. In my previous article DATEPART SQL FUNCTION, we explored to retrieve specific part from the date such as day, year, month, quarter, day of the year.

通常,我们在SQL Server中使用日期数据类型。 我们还需要对日期进行操作。 在上一篇文章DATEPART SQL FUNCTION中 ,我们探索了从日期中检索特定的部分,例如日,年,月,季度,年中的某日。

We can use the SQL SERVER DATEADD function to add or subtract specific period from a gives a date.

我们可以使用SQL SERVER DATEADD函数从给定日期中添加或减去特定时间段。

句法 (Syntax )

DATEADD (datepart, number, date)

DATEADD(日期部分,数字,日期)

  • Datepart: It specifies the part of the date in which we want to add or subtract specific time interval. It can have values such as year, month, day, and week. We will explore more in this in the example section Datepart :它指定要在其中添加或减去特定时间间隔的日期部分。 它可以具有诸如年,月,日和周的值。 我们将在示例部分中对此进行更多探索
  • Number: It is the number by which we want to increase or decrease date. It should be an integer 数字:这是我们要增加或减少日期的数字。 应该是整数
  • Date: We can specify the date here. In this date, we want to add a specified number on datepart 日期:我们可以在此处指定日期。 在此日期,我们要在datepart上添加一个指定的数字

Suppose we want to add ten days to the current date. In this example, the variables would be

假设我们要在当前日期前增加十天。 在此示例中,变量为

  • Day
  • 5 5
  • Date: Getdate() – Current date
  • 日期: Getdate() – 当前日期

通过示例探索SQL SERVER DATEADD函数 (Explore the SQL SERVER DATEADD function with examples)

Example

Datepart

Query with output

Add 10 days to specified date

dd

d

SELECT DATEADD(dd, 10, '2019/04/29');

Output – 2019-05-09 00:00:00.000

Subtract one day from a specified date

dd

D

Output -2019-04-28 00:00:00.000

Add two years in a specified date

YYYY

YY

SELECT DATEADD(YY,2, '2019/04/29');

Output – 2021-04-29 00:00:00.000

Subtract three years from a specified date

YYYY

YY

Output – 2016-04-29 00:00:00.000

Add 4 Months in specified date

MM

SELECT DATEADD(MM,5, '2019/04/29');

Output – 2019-09-29 00:00:00.000

Add 2 hours to a date

HH

Output – 2019-04-29 02:00:00.000

In this example, we did not specify any time with the input date. By default, SQL Server considers time 00:00.000

Subtract 120 minutes from date

MM

SELECT DATEADD(Mi,-120, '2019/04/29')

Output – 2019-04-28 22:00:00.000

Add 1 quarter in specified date

QQ

Output – 2019-07-29 00:00:00.000

Add 100 days of the year in a specified date

DY

SELECT DATEADD(DY,100, '2019/04/29')

Output – 2019-08-07 00:00:00.000

Invalid value – Add 12578995 years in specified date

Year

We cannot specify invalid values or out of range values in the SQL SERVER DATEADD function. We get following error message Output – Msg 517, Level 16, State 1, Line 1: Adding a value to a ‘datetime’ column caused an overflow.

Out of range number value – In the DATEADD number parameter, we can specify only integer values.

Integer value range: -231 (-2,147,483,648) to 231-1 (2,147,483,647)

SELECT DATEADD(year,2147483648, '20060731');

In this example, we specified value 2147483648 in number parameter. This value does not fall inside an integer range. Once we execute this query, we get the following error message.
Msg 8115, Level 16, State 2, Line 3
Arithmetic overflow error converting expression to data type int.

日期部分

查询输出

在指定日期增加10天

dd

d

产出– 2019-05-09 00:00:00.000

从指定日期减去一天

dd

d

SELECT DATEADD(dd,-1, '2019/04/29');

输出 -2019-04-28 00:00:00.000

在指定的日期增加两年

YYYY

YY

输出– 2021-04-29 00:00:00.000

从指定日期减去三年

YYYY

YY

SELECT DATEADD(YY,-3, '2019/04/29');

产出– 2016-04-29 00:00:00.000

在指定日期增加4个月

MM

产出– 2019-09-29 00:00:00.000

将日期增加2个小时

H

SELECT DATEADD(HH,2, '2019/04/29');

产出– 2019-04-29 02:00:00.000

在此示例中,我们没有使用输入日期指定任何时间。 默认情况下,SQL Server考虑时间00:00.000

从日期减去120分钟

MM

产出– 2019-04-28 22:00:00.000

在指定日期增加1个季度

QQ

SELECT DATEADD(QQ,1, '2019/04/29')

产出– 2019-07-29 00:00:00.000

在指定日期添加一年中的100天

DY

产出 – 2019-08-07 00:00:00.000

值无效-在指定日期增加了12578995年

SELECT DATEADD(year,12578995, '20060731');

我们不能在SQL SERVER DATEADD函数中指定无效值或超出范围的值。 我们收到以下错误消息输出 – 消息517,级别16,状态1,第1行:向“ datetime”列添加一个值导致溢出。

超出范围的数字值–在DATEADD数字参数中,我们只能指定整数值。

整数值范围 :-231(-2,147,483,648)到231-1(2,147,483,647)

在此示例中,我们在number参数中指定了值2147483648。 该值不在整数范围内。 一旦执行此查询,我们将收到以下错误消息。
Msg 8115,第16级,州2,第3行
将表达式转换为数据类型int的算术溢出错误。

SQL SERVER DATEADD函数中的数据类型 (Data types in the SQL SERVER DATEADD function)

We can use the following data type in date expression.

我们可以在日期表达式中使用以下数据类型。

  • date 日期
  • DateTime 约会时间
  • datetimeoffset 日期时间偏移
  • datetime2 datetime2
  • smalldatetime 小日期时间
  • time 时间

In the following query, we declared a variable @date having a datetime2 datatype. We can use the DATEADD SQL function as per the following query.

在以下查询中,我们声明了一个具有datetime2数据类型的变量@date。 我们可以按照以下查询使用DATEADD SQL函数。

DECLARE @Date datetime2;
SET @Date = '2019-04-29 01:01:01.1111111';
Select DATEADD(quarter,1,@Date),
DATEADD(month,11,@Date)
,DATEADD(dayofyear,265,@Date)
, DATEADD(day,265,@Date)
, DATEADD(week,4,@Date)
, DATEADD(weekday,29,@Date)
, DATEADD(hour,11,@Date)
, DATEADD(minute,59,@Date)
, DATEADD(second,01,@Date)
, DATEADD(millisecond,1,@Date);

使用SQL SERVER DATEADD函数从指定日期范围内的表中获取记录 (Using the SQL SERVER DATEADD function to get records from a table in specified date range)

We can use the DATEADD SQL function to retrieve records from a table for a period. In the following query, we specified a date with parameter @Startdate. We want to retrieve records from Orders table. We need to get records between @StartDate and @Enddate ( add 1 hour in start date) .

我们可以使用DATEADD SQL函数从表中检索一段时间的记录。 在以下查询中,我们使用参数@Startdate指定了一个日期。 我们要从“订单”表中检索记录。 我们需要获取@StartDate和@Enddate之间的记录(在开始日期中添加1小时)。

DECLARE @StartDate DATETIME= '2013-05-01 11:00.000';
DECLARE @Hours INT= 1;
SELECT OrderID, LastEditedWhen
FROM [WideWorldImporters].[Sales].[Orders]
WHERE LastEditedWhen BETWEEN @StartDate AND DATEADD(HOUR, @Hours, @StartDate);

We get the following output.

我们得到以下输出。

使用SQL SERVER DATEADD函数获取日期或时间差 (Using the SQL SERVER DATEADD function to get date or time difference)

We can use the DATEADD SQL function to get time difference between the start date and end date. Many times, we want to use the SQL SERVER DATEADD function to get date difference. For example, we want to know how long it took to complete an order or how long it took to reach from home to office.

我们可以使用DATEADD SQL函数获取开始日期和结束日期之间的时差。 很多时候,我们想使用SQL SERVER DATEADD函数来获取日期差。 例如,我们想知道完成订单需要多长时间,或者从家到办公室要花费多长时间。

Execute the following query to get the difference between starttime and endtime. We use the DATEADD SQL function along with the DATEDIFF SQL function.

执行以下查询以获取开始时间和结束时间之间的差异。 我们将DATEADD SQL函数与DATEDIFF SQL函数一起使用。

DECLARE @StartTime DATETIME= '2019-04-29 20:30:00', @EndTime DATETIME= '2019-04-30 01:00:00';
SELECT DATEADD(Minute,DATEDIFF(Minute, @StartTime, @EndTime),0) AS ElapsedTime;

It gives the elapsed time in minutes. We specified value 0 in the DateADD SQL function. It takes date value 1900-01-01 00:00:00.000

它以分钟为单位给出经过的时间。 我们在DateADD SQL函数中指定了值0 。 它需要日期值1900-01-01 00:00:00.000

We can use SQL Convert date format to represent this in HH:MM:SS format.

我们可以使用SQL Convert日期格式将其表示为HH:MM:SS格式。

DECLARE @StartTime DATETIME= '2019-04-29 20:30:00', @EndTime DATETIME= '2019-04-30 01:00:00';
SELECT CONVERT(VARCHAR(8), DATEADD(Minute, DATEDIFF(Minute, @StartTime, @EndTime), 0), 108) AS ElapsedTime;

It gives the time difference in HH:MM:SS format as shown in the following image.

如下图所示,它以HH:MM:SS格式给出了时差。

将SQL SERVER DATEADD函数结果指定为新列 (Specify the SQL SERVER DATEADD function result as a new column )

We can use the SQL SERVER DATEADD function to get a new column after adding the required date value. In the following query, we want to add two days in the start date and represent this as a new column.

添加所需的日期值后,我们可以使用SQL SERVER DATEADD函数获取新列。 在以下查询中,我们要在开始日期添加两天,并将其表示为新列。

DECLARE @StartDate DATETIME= '2013-05-01 11:00.000';
DECLARE @Day INT= 2;
SELECT OrderID, LastEditedWhen, DATEADD(day, @Day, LastEditedWhen) AS NewDateColumn
FROM [WideWorldImporters].[Sales].[Orders];

DATEADD SQL函数中的标量子查询和标量函数 (Scalar sub queries and scalar functions in the DATEADD SQL function)

We can use the SQL SERVER DATEADD function with scalar sub queries and scalar functions as well. In the following query, we want to add number of days in max date value of LastEditedWhen in the Sales.orders table.

我们可以将SQL SERVER DATEADD函数与标量子查询和标量函数一起使用。 在以下查询中,我们要在Sales.orders表的LastEditedWhen的最大日期值中添加天数

The first subquery gives the number 16496 and second sub query provides a date. We used the SQL SERVER DATEADD function to add number of days, and we get the following output.

第一个子查询提供数字16496,第二个子查询提供日期。 我们使用SQL SERVER DATEADD函数添加天数,并获得以下输出。

SELECT DATEADD(dd,
(SELECT TOP 1 BusinessEntityIDFROM Person.Person
),
(SELECT MAX(LastEditedWhen)FROM [WideWorldImporters].[Sales].[Orders]
));

SQL SERVER DATEADD函数中的数值表达式 (Numeric expressions in the SQL SERVER DATEADD function)

We can use numeric expressions as well in SQL SERVER DATEADD function. In the following query, we use a numeric expression to calculate the number and give us an output.

我们也可以在SQL SERVER DATEADD函数中使用数字表达式。 在以下查询中,我们使用数字表达式计算数字并提供输出。

  SELECT GETDATE() AS CurrentDate, DATEADD(month, -(12 / 6), GETDATE()) AS ModifiedDate;

将DATEADD与Rank函数一起使用 (Using DATEADD with the Rank function)

We can use the DATEADD SQL function in a rank function as well. We can use it for the number argument. In the following query, you can see Row_Number() function to use number parameter and the values as date parameter.

我们也可以在rank函数中使用DATEADD SQL函数。 我们可以将其用于number参数。 在以下查询中,您可以看到Row_Number()函数将数字参数和值用作日期参数。

SELECT OrderID, CustomerID, DATEADD(day, ROW_NUMBER() OVER(ORDER BY CustomerPurchaseOrderNumber), SYSDATETIME()) AS 'Row Number'
FROM [WideWorldImporters].[Sales].[Orders];

结论 (Conclusion)

In this article, we explored various uses and examples of the DATEADD SQL function. It allows us to add or subtract datepart values from the specified date. I hope you like this article. Feel free to provide feedback in the comments below.

在本文中,我们探讨了DATEADD SQL函数的各种用法和示例。 它允许我们从指定日期添加或减去datepart值。 希望您喜欢这篇文章。 请随时在下面的评论中提供反馈。

翻译自: https://www.sqlshack.com/dateadd-sql-function-introduction-and-overview/

sql dateadd函数

sql dateadd函数_DATEADD SQL函数简介和概述相关推荐

  1. MSSQL Sql加密函数 hashbytes 用法简介

    原文:MSSQL Sql加密函数 hashbytes 用法简介 转自:http://www.maomao365.com/?p=4732 一.mssql sql hashbytes 函数简介 hashb ...

  2. SQL With As 用法Sql 四大排名函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE)简介

    Sql 四大排名函数(ROW_NUMBER.RANK.DENSE_RANK.NTILE)简介 排名函数是Sql Server2005新增的功能,下面简单介绍一下他们各自的用法和区别.我们新建一张Ord ...

  3. sql dateadd函数_什么是SQL Server DATEADD()函数?

    sql dateadd函数 Hey, folks! In this article, we will be focusing on SQL Server DATEADD() function in d ...

  4. sql:函数:开窗函数简介

    与聚合函数一样,开窗函数也是对行集组进行聚合计算,但是普通聚合函数每组只能返回一个值,而开窗函数可以每组返回多个值. 实验一 比如我们想查询每个工资小于5000元的员工信息(城市以及年龄),并且在每行 ...

  5. 学习SQL:SQL Server日期和时间函数

    So far, we haven't talked about SQL Server date and time functions. Today we'll change that. We'll t ...

  6. 学习SQL:使用日期和时间函数创建SQL Server报表

    In the previous two articles of this series, we've discussed how to create a report and how to use b ...

  7. SQL Server Window Function 窗体函数读书笔记二 - A Detailed Look at Window Functions

    这一章主要是介绍 窗体中的 Aggregate 函数, Rank 函数, Distribution 函数以及 Offset 函数. Window Aggregate 函数 Window Aggrega ...

  8. oracle stdevp函数,适用于sql初学,学习sql语句的一些整理,其中大多是oracle的

    ****前期 Windows中运行cmd的Sqlplus中 设置每行显示的数据长度: Set linesize 数字; 设置每页显示的数据行数: Set pagesinze 数字; oralce中切换 ...

  9. sql server编程之 T-SQL函数

    T-SQL函数 学习系统函数.行集函数和Ranking函数:重点掌握字符串函数.日期时间函数和数学函数的使用参数以及使用技巧 重点掌握用户定义的标量函数以及自定义函数的执行方法 掌握用户定义的内嵌表值 ...

最新文章

  1. python好学嘛-爬虫Python入门好学吗?学什么?
  2. 应用c语言编辑画图程序,应用C语言编辑画图程序
  3. ArrayList类contains方法实现原理
  4. arduino openmv 显示图像_OpenMV与Arduino NUO的连接方式
  5. C++之关于初始化列表(Initialization List)的一个补充示例
  6. 杭电3068 最长回文 最长回文的manacher算法
  7. android高德地图自动缩放比例,【Android】高德地图 缩放级别及像素以及地图上的点转化成屏幕上的点...
  8. Postman:ResponseHeader存在多个Set-Cookie时,教你获取Cookie值
  9. jquery dialog 打开的时候自动聚焦解决方法
  10. Java的静态数组和动态数组
  11. LOGO以及手绘签名完美导入CAD
  12. 050 XSS通关小游戏——xss challenge
  13. 微信共享智能充电桩小程序开发功能方案
  14. 智慧交通,迎来产业谍战丨产业特稿
  15. docker部署环境
  16. C++:实现量化SMM Caplet α 校准测试实例
  17. 无线MESH自组网系统
  18. 小学计算机课认识键盘,教学设计:《认识键盘》
  19. 使用postman interceptor拦截浏览器和手机请求
  20. 数据结构--表达式括号匹配和运算

热门文章

  1. 【腾讯Bugly干货分享】iOS黑客技术大揭秘
  2. Notifucation 通知
  3. 你想要的Python面试题都在这里了!
  4. linux新建文件加入运行,linux新建文件命令是什么_网站服务器运行维护,linux,新建文件...
  5. 微信小程序 实现个人用户界面
  6. 从pcl删除点_PCL常用操作
  7. git冲突出现的原因及解决方案
  8. 华为服务器操作系统开源!
  9. MySql报错:You can‘t specify target table ‘t‘ for update in FROM clause
  10. noip2005篝火晚会