MS SQL比较date?
我有2个date(date时间):
date1 = 2010-12-31 15:13:48.593
date2 = 2010-12-31 00:00:00.000
同一天,只是不同的时间。 使用<=比较date1和date2是不行的,因为date1时间。 所以date1 <= date2是错的,但应该是真的。 我可以比较他们只看年,月和日,所以他们是一样的吗? 它的SQL Server 2008。
谢谢 :)
SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...
应该做你需要的。
testing用例
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 YN
使用DATEDIFF
函数的date部分。
SELECT ... FROM ... WHERE DATEDIFF(day, date1, date2) >= 0
请注意,如果要testingdate1
<= date2
则需要testingDATEDIFF(day, date1, date2) >= 0
,或者可以testingDATEDIFF(day, date2, date1) <= 0
。
简单的一行解决scheme是
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
您可以尝试使用除“dd”以外的其他选项
我总是用DateDiff(day,date1,date2)来比较两个date。
签出以下示例。 只需将其复制并在Ms sql服务器中运行。 另外,请在31日至30日的变更date之前尝试,确认结果
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
尝试这个:
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