MS SQL比较日期?

时间:2011-01-25 13:25:47

标签: sql-server tsql sql-server-2008 date

我有2个日期(日期时间):

date1 = 2010-12-31 15:13:48.593
date2 = 2010-12-31 00:00:00.000

它在同一天,只是不同的时间。使用< =比较date1和date2因为date1时间而无效。所以date1< = date2是错误的,但应该是真的。我可以通过查看年,月和日来比较它们,以便它们是相同的吗?它的SQL Server 2008。

谢谢:)

5 个答案:

答案 0 :(得分:80)

SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...

应该做你需要的。

测试用例

WITH dates(date1, date2, date3, date4)
     AS (SELECT CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME),
                CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME))
SELECT CASE
         WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITH_CAST,
       CASE
         WHEN date3 <= date4 THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITHOUT_CAST
FROM   dates 

返回

COMPARISON_WITH_CAST   |  COMPARISON_WITHOUT_CAST
Y                         N

答案 1 :(得分:62)

使用DATEDIFF函数,其日期部分为day

SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0

请注意,如果您要测试date1&lt; = date2,那么您需要测试DATEDIFF(day, date1, date2) >= 0,或者您可以测试DATEDIFF(day, date2, date1) <= 0

答案 2 :(得分:3)

简单的一行解决方案是

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')=0

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')<=1

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')>=1

除了&#34; dd&#34;

之外,您可以尝试使用此选项

答案 3 :(得分:0)

我总是使用DateDiff(day,date1,date2)来比较两个日期。

结帐以下示例。只需复制并在Ms sql server中运行即可。 此外,尝试更改日期为31 dec至30 dec并检查结果

BEGIN

declare @firstDate datetime
declare @secondDate datetime


declare @chkDay int

set @firstDate ='2010-12-31 15:13:48.593'
set @secondDate ='2010-12-31 00:00:00.000'

set @chkDay=Datediff(day,@firstDate ,@secondDate )

if @chkDay=0
    Begin
        Print 'Date is Same'
    end
else
    Begin
        Print 'Date is not Same'
    end
End

答案 4 :(得分:-1)

试试这个:

BEGIN

declare @Date1 datetime
declare @Date2 datetime

declare @chkYear int
declare @chkMonth int
declare @chkDay int
declare @chkHour int
declare @chkMinute int
declare @chkSecond int
declare @chkMiliSecond int

set @Date1='2010-12-31 15:13:48.593'
set @Date2='2010-12-31 00:00:00.000'

set @chkYear=datediff(yyyy,@Date1,@Date2)
set @chkMonth=datediff(mm,@Date1,@Date2)
set @chkDay=datediff(dd,@Date1,@Date2)
set @chkHour=datediff(hh,@Date1,@Date2)
set @chkMinute=datediff(mi,@Date1,@Date2)
set @chkSecond=datediff(ss,@Date1,@Date2)
set @chkMiliSecond=datediff(ms,@Date1,@Date2)

if @chkYear=0 AND @chkMonth=0 AND @chkDay=0 AND @chkHour=0 AND @chkMinute=0 AND @chkSecond=0 AND @chkMiliSecond=0
    Begin
        Print 'Both Date is Same'
    end
else
    Begin
        Print 'Both Date is not Same'
    end
End