DATEDIFF不返回整数值T-SQL

时间:2017-12-19 21:45:24

标签: sql sql-server datetime sql-server-2012

我正在尝试查看在SQL Server 2012中向表中插入一些值所花费的时间。

我正在尝试这样做:

DECLARE @starttime DATETIME
DECLARE @timetook DATETIME

CREATE TABLE MyTable (id INT, name CHAR(10));

SET @starttime = SYSDATETIME()

INSERT INTO MyTable (id, name) 
VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe'),
       (4, 'Boby'), (5, 'Peters'), (6, 'Joey'),
       (7, 'Bobs'), (8, 'Petery'), (9, 'Joes');

SET @timetook = DATEDIFF(ss, @starttime, SYSDATETIME())

SELECT @timetook

返回1900-01-01 00:00:00.000。根据{{​​1}} docs,它应为datediff或整数值。因为我花了几秒钟,所以我应该在几秒钟内得到这个数字。 (对于此示例,它应为0但没有1900-01-01)

我在这里缺少什么?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

将@timetook声明为datetime会给你一个datetimeresult。 datetime = 0具体为1900-01-01 00:00:00.000

declare @starttime datetime
declare @timetook int --Issue was this declaration as datetime

CREATE TABLE MyTable (id int, name char(10));

set @starttime = SYSDATETIME()

INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe'),
                                      (4, 'Boby'), (5, 'Peters'), (6, 'Joey'),
                                      (7, 'Bobs'), (8, 'Petery'), (9, 'Joes');
set @timetook = DATEDIFF(ss, @starttime, SYSDATETIME())

select @timetook

通过将@timetook声明为int,您将获得所需的结果:0