Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two date values using SQL [duplicate]

Tags:

sql

How to compare two dates the first column table one 2013-04-04 05:47:52.000 the second one from other table 2010-01-01 00:00:00.000. I want to compare just yy/month/day; if they are equal, I get second id table.

like image 258
user2586714 Avatar asked Jul 22 '13 23:07

user2586714


2 Answers

For Sql Server you can do this:

CAST(table1date AS DATE) = CAST(table2date AS DATE)

Example of how it could be used:

declare @dateTime1 as datetime = '2013-04-04 05:47:52.000'
declare @dateTime2 as datetime = '2013-04-04 00:00:00.000'

if CAST(@dateTime1 AS DATE) = CAST(@dateTime2 AS DATE)
    print 'yy mm dd is the same'
else
    print 'not the same'

Or using tables:

declare @dateTime1 as datetime = '2013-04-04 05:47:52.000'
declare @dateTime2 as datetime = '2011-04-04 00:00:00.000'

declare @table1 table (id1 int, dt1 datetime)
declare @table2 table (id2 int, dt2 datetime, table1id int)
insert into @table1 values (1, @dateTime1)
insert into @table2 values (2, @dateTime2, 1)

select case when CAST(@dateTime1 AS DATE) = CAST(@dateTime2 AS DATE) then t2.id2 else t2.table1id end as id
from @table1 t1 join @table2 t2 on t1.id1 = t2.table1id
like image 105
PostureOfLearning Avatar answered Sep 22 '22 14:09

PostureOfLearning


IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)
like image 45
Saritha.S.R Avatar answered Sep 20 '22 14:09

Saritha.S.R