简体   繁体   English

SQL Server 2016:使用DATETIME加入DATETIME2(3)

[英]SQL Server 2016 : join DATETIME2(3) with DATETIME

I'm getting unexpected results when joining on a DATETIME2(3) and a DATETIME column with PK, in SQL Server 2016. 在SQL Server 2016中加入带有PK的DATETIME2(3)DATETIME列时,我得到了意想不到的结果。

I have the following table: 我有下表:

CREATE TABLE DATETIME_TEST 
(
    [DATETIME] DATETIME NOT NULL,
    [DATETIME2_3] DATETIME2(3)
);

ALTER TABLE DATETIME_TEST 
    ADD CONSTRAINT PK_DATETIME_TEST PRIMARY KEY ([DATETIME]);

INSERT INTO DATETIME_TEST ([DATETIME], [DATETIME2_3])
VALUES ('20020202 02:02:02.000', '20020202 02:02:02.000'), 
       ('20020202 02:02:02.003', '20020202 02:02:02.003'), 
       ('20020202 02:02:02.007', '20020202 02:02:02.007'),
       ('2019-04-28 07:23:29.447', '2019-04-28 07:23:29.447');

SELECT * 
FROM DATETIME_TEST 
WHERE CONVERT(DATETIME2(3), [DATETIME]) = [DATETIME2_3]

The results : 结果 :

DATETIME                  DATETIME2_3
-------------------------------------------------
2002-02-02 02:02:02.000   2002-02-02 02:02:02.000
2002-02-02 02:02:02.003   2002-02-02 02:02:02.003
2002-02-02 02:02:02.007   2002-02-02 02:02:02.007
2019-04-28 07:23:29.447   2019-04-28 07:23:29.447

As you can see above, the values are equal. 如您所见,值相等。

SELECT      
    a.DATETIME,
    a.DATETIME2_3
FROM
    DATETIME_TEST a
INNER JOIN 
    DATETIME_TEST b ON CONVERT(DATETIME2(3), a.[DATETIME]) = b.[DATETIME2_3]

The results : 结果 :

DATETIME2_3                  DATETIME
-----------------------------------------------------
2002-02-02 02:02:02.000      2002-02-02 02:02:02.000

Although the values are equal, I only get some of the rows. 虽然值相等,但我只获得了一些行。

But if I remove the PK or change compatibility level to COMPATIBILITY_LEVEL = 120 , then I get all rows as expected 但是,如果我删除PK或将兼容级别更改为COMPATIBILITY_LEVEL = 120 ,那么我会按预期获得所有行

Is it a bug ? 这是一个错误吗?

Is there a better way to do this join. 有没有更好的方法来进行此加入。

Note: I join to the same table only for the simplicity of the example in real life I join between 2 different tables. 注意:我加入到同一个表只是为了简化现实生活中的例子,我加入了两个不同的表。

Actually, I have come across this as well. 实际上,我也遇到过这个问题。 It is definitely a valid question to Microsoft SQL Server Team. 对于Microsoft SQL Server团队来说,这绝对是一个有效的问题。 Thank you for taking the time to raising this bug. 感谢您抽出宝贵时间提出此错误。

But as an alternative solution, you should rather try to convert the 'richer' datatype (DATETIME2) to the 'poorer' datatype (DATETIME) as backward compatible way. 但作为替代解决方案,您应该尝试将'richer'数据类型(DATETIME2)转换为'较差'数据类型(DATETIME)作为向后兼容的方式。 And then it would give you the results you are looking for: 然后它会给你你想要的结果:

SELECT      
    a.DATETIME,
    a.DATETIME2_3
FROM
    DATETIME_TEST a
INNER JOIN 
    DATETIME_TEST b ON a.[DATETIME] = CONVERT(DATETIME, b.[DATETIME2_3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM