如何使用SQL比较两个日期值

时间:2013-07-22 23:24:46

标签: sql

如何比较第一列表格的两个日期2013-04-04 05:47:52.000第二列其他表格2010-01-01 00:00:00.000。 我想比较yy / month / day;如果它们相等,我会得到第二个id表。

3 个答案:

答案 0 :(得分:8)

对于Sql Server,您可以这样做:

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

如何使用它的示例:

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'

或使用表格:

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

答案 1 :(得分:5)

IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)

答案 2 :(得分:4)

通过比较你的意思是找到差异?

怎么样

DATEDIFF(datepart,startdate,enddate)

http://www.w3schools.com/sql/func_datediff.asp