How to compare only date part when delivery date is today

烂漫一生 提交于 2019-12-20 12:28:11

问题


I'm trying to create a report that gets records from a SQL Server database where the delivery date is today.

I've tried

select * from (tablename)
where delivery_date = getdate()

Although that didn't give me any errors, it didn't give me any records either.

I'm assuming it is because all dates are like:

2016-03-15 00:00:00.000

Perhaps, I need to truncate the date to remove the time-stamp and then try?


回答1:


You can try a query like below

select * from (tablename)
where CAST(delivery_date as date) = CAST(getdate() as date)

Also if all delivery dates have time part like 00:00:00.000 for sure then

select * from (tablename)
where delivery_date = CAST(getdate() as date) 

would work as good.




回答2:


If delivery_date is always midnight (00:00:00.000), then compare it like this:

select * from (tablename)
where delivery_date = datediff(d, 0, getdate())

Using datediff like this is a quick way to truncate the time part of a datetime value.




回答3:


I'd just create 2 params. One for StartTime and one for EndTime and use those in my query.

DECLARE @StartTime DATETIME,
        @EndTime DATETIME 

SET @StartTime = DATEDIFF(d,0,GETDATE())
SET @EndTime = DATEADD(d,1,@StartTime)

SELECT  *
FROM    [tablename]
WHERE   delivery_date >= @StartTime
        AND delivery_date < @EndTime



回答4:


Yo need to remove the time part of the delivery_date field AND the GETDATE() value.

SELECT *
FROM  (tablename)
WHERE DATEADD(dd, DATEDIFF(dd, 0, delivery_date), 0) = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)



回答5:


Try this:

DECLARE @Today DATETIME
SET @Today= CONVERT(date, getdate())

select * from (tablename)
where delivery_date = @Today


来源:https://stackoverflow.com/questions/36018833/how-to-compare-only-date-part-when-delivery-date-is-today

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