我在tsql中使用dateadd函数,我收到溢出错误。这是我的代码:
insert into dbo.PayPeriodLookups (PayPeriodEndDate, PayPeriodStartDate)
values
(20161015, dateadd(day, -13, '2016/10/15')),
(20161029, dateadd(day, -13, '2016/10/29')),
(20161112, dateadd(DAY, -13, '2016/11/12')),
(20161126, dateadd(DAY, -13, '2016/11/26')),
(20161210, dateadd(DAY, -13, '2016/12/10')),
(20161224, dateadd(Day, -13, '2016/12/24')),
(20170107, dateadd(day, -13, '2017/01/07')),
(20170121, dateadd(day, -13, '2017/01/21'))
当我尝试执行此脚本时,我一直收到此错误: '将表达式转换为数据类型datetime的算术溢出错误。 该声明已被终止。'
任何人都知道我为什么会收到此错误?我认为这是dateadd函数的工作方式......
答案 0 :(得分:2)
这不是DATEADD()
的问题,这是您要插入的PayPeriodEndDate
值的问题。您使用INT
值来表示日期,何时应将它们用单引号括起来。
您正在尝试从INT
到DATETIME
进行隐式演员,而这不能按照您的方式进行。表示日期的正确方法是'yyyy-mm-dd'
。请改用以下内容:
Values
(Cast('2016-10-15' As DateTime), DateAdd(Day, -13, '2016-10-15')),
(Cast('2016-10-29' As DateTime), DateAdd(Day, -13, '2016-10-29')),
(Cast('2016-11-12' As DateTime), DateAdd(Day, -13, '2016-11-12')),
(Cast('2016-11-26' As DateTime), DateAdd(Day, -13, '2016-11-26')),
(Cast('2016-12-10' As DateTime), DateAdd(Day, -13, '2016-12-10')),
(Cast('2016-12-24' As DateTime), DateAdd(Day, -13, '2016-12-24')),
(Cast('2017-01-07' As DateTime), DateAdd(Day, -13, '2017-01-07')),
(Cast('2017-01-21' As DateTime), DateAdd(Day, -13, '2017-01-21'))
答案 1 :(得分:1)
引用你的int值,如下图所示
Declare @T1 table (PayPeriodEndDate datetime,PayPeriodStartDate datetime)
Insert Into @T1 values
('20161015', dateadd(day, -13, '2016/10/15')),
('20161029', dateadd(day, -13, '2016/10/29')),
('20161112', dateadd(DAY, -13, '2016/11/12')),
('20161126', dateadd(DAY, -13, '2016/11/26')),
('20161210', dateadd(DAY, -13, '2016/12/10')),
('20161224', dateadd(Day, -13, '2016/12/24')),
('20170107', dateadd(day, -13, '2017/01/07')),
('20170121', dateadd(day, -13, '2017/01/21'))
Select * from @T1
或者将int值转换为varchar(8)
Declare @T2 table (PayPeriodEndDate datetime,PayPeriodStartDate datetime)
Insert Into @T2 values
(cast(20161015 as varchar(8)), dateadd(day, -13, '2016/10/15')),
(cast(20161029 as varchar(8)), dateadd(day, -13, '2016/10/29')),
(cast(20161112 as varchar(8)), dateadd(DAY, -13, '2016/11/12')),
(cast(20161126 as varchar(8)), dateadd(DAY, -13, '2016/11/26')),
(cast(20161210 as varchar(8)), dateadd(DAY, -13, '2016/12/10')),
(cast(20161224 as varchar(8)), dateadd(Day, -13, '2016/12/24')),
(cast(20170107 as varchar(8)), dateadd(day, -13, '2017/01/07')),
(cast(20170121 as varchar(8)), dateadd(day, -13, '2017/01/21'))
Select * from @T2