SQL ignore nanoseconds when comparing datetime2

感情迁移 提交于 2019-12-01 18:56:00

This all depends on what precision you want to work with. Do you want to match just the date portion or the date and time without milliseconds?

Here's a few ways to change the precision of the data:

CREATE TABLE #dates ( val DATETIME2 );

INSERT INTO #dates ( val ) VALUES ( SYSDATETIME());   
INSERT INTO #dates ( val ) VALUES ( SYSDATETIME());    
INSERT INTO #dates ( val ) VALUES ( SYSDATETIME());

SELECT d.val AsOriginalValue ,
       CAST(d.val AS DATETIME) AsDateTime ,
       CAST(d.val AS DATETIME2(0)) AsDateTime2_0 ,
       CAST(d.val AS DATE) AsDate
FROM   #dates AS d;

DROP TABLE #dates;

Results in:

AsOriginalValue             AsDateTime              AsDateTime2_0             AsDate
--------------------------- ----------------------- ---------------------- ----------
2018-01-25 14:35:14.3660549 2018-01-25 14:35:14.367 2018-01-25 14:35:14    2018-01-25
2018-01-25 14:35:14.3665552 2018-01-25 14:35:14.367 2018-01-25 14:35:14    2018-01-25
2018-01-25 14:35:14.3670555 2018-01-25 14:35:14.367 2018-01-25 14:35:14    2018-01-25

NOTE: beware of rounding.

Try a CAST to DATETIME

select t1.* from Table1 t1, Table12 t2 
where CAST(t1.tradeDateTime as DATETIME) = CAST(t2.tradeDate as DATETIME)

A test

DECLARE @1 DATETIME2='2018-01-24 10:51:23.9976180'
, @2 DATETIME2 = '2018-01-24 10:51:23.9970000'


SELECT @1, @2,  Test =CASE WHEN CAST(@1 AS DATETIME) = CAST(@2 AS
DATETIME) THEN 1 ELSE 0 END

Cast the dates as DateTime as this will cast the value to only 3 decimal places. Also, please use prober JOINS:

SELECT t1.*
FROM Table1 t1
    JOIN Table12 t2 ON t2.Joinable_ID = t1.Joinable_ID
WHERE CAST(t1.tradeDateTime AS DATETIME) = CAST(t2.tradeDate AS DATETIME)

Using functions in the WHERE clause can cause performance problems. You might get better speed with a CTE approach:

 with t1 as 
           (select cast(tradeDateTime as datetime) as tradeDateTimeNoTime
            from Table1)
    , t2 as 
           (select cast(tradeDate as datetime) as tradeDateNoTime 
            from Table2)

 select t1.*
      , t2.* 
 from t1 
 inner join t2 
 on t1.tradeDateTimeNoTime = t2.tradeDateNoTime

Whichever solution you use, I would definitely recommend using the explicit JOIN syntax and not the comma syntax. Final note, that joining on a datetime field isn't ideal to begin with so you may want to consider an approach that uses IDs in both tables.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!