How do I compare two timestamps as dates in SQL Se

2019-09-17 04:35发布

I want to run a query to bring back that occurred on or after a date where the input date is a timestamp and the and the table is a timestamp. The problem i have is right now results are getting excluded based on time so some go missing. Refer to below sample for details

Sample SQL

Select *
from table
where DateTime >= InputDateTime

Sample Table

Row | DateTime
1   | 2015-01-16 23:12:11
2   | 2015-01-15 06:12:24
3   | 2015-01-14 23:12:24
4   | 2015-01-15 23:12:24
5   | 2015-01-12 23:12:24

Expected result if InputDateTime = 2015-01-15 12:13:24

Row | DateTime
1   | 2015-01-16 23:12:11
2   | 2015-01-15 06:12:24
4   | 2015-01-15 23:12:24

2条回答
2楼-- · 2019-09-17 05:05

If you want to consider only the date, then remove the time component:

where datetime >= cast(getdate() as date)

Of courese, you can do this for a variable or column as well:

where datetime >= cast(@inputdatetime as date)
查看更多
Fickle 薄情
3楼-- · 2019-09-17 05:06

Now that I understand that you are wanting to compare based solely off of date, I am changing my code to reflect a way to do so:

DECLARE @inputDateTime DATETIME = '2015-01-15 12:13:24'

-- DROP TABLE [#testTable]
CREATE TABLE [#testTable]
(
[Row] INT IDENTITY(1,1),
[DateTime] DATETIME
)

INSERT INTO [#testTable]
    (
    [DateTime]
    )
VALUES
    ('2015-01-16 23:12:11'),
    ('2015-01-15 06:12:24'),
    ('2015-01-14 23:12:24'),
    ('2015-01-15 23:12:24'),
    ('2015-01-12 23:12:24')

SELECT
    *
FROM
    [#testTable]
WHERE
    [DateTime] >= CONVERT(DATETIME,FLOOR(CONVERT(FLOAT,@inputDateTime)))
查看更多
登录 后发表回答