【问题标题】:DATEDIFF does not return an integer value T-SQLDATEDIFF 不返回整数值 T-SQL
【发布时间】:2017-12-19 21:45:23
【问题描述】:

我正在尝试查看在 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。根据datediffdocs,应该是00:00:00.000或者整数值。由于我正在计算秒数,因此我应该以秒为单位获得数字。 (对于这个例子,它应该是 0 但没有 1900-01-01)

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

【问题讨论】:

  • 您的 timetook 变量是一个日期时间,因此表示是日期时间。尝试作为 int。
  • 应该将其作为答案发布@JacobH

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


【解决方案1】:

将@timetook 声明为日期时间将为您提供一个日期时间结果。而 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

【讨论】:

    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 2018-09-02
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多