I'm getting unexpected results when joining on a DATETIME2(3)
and a DATETIME
column with PK, in SQL Server 2016.
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
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.