Bala
Bala

Reputation: 11234

How do I compare 2 dates in SQL Server

I have a string 2021-02-23T06:58:51 that I want to check if it is greater than another date. When I do the below I get an error. Tried CAST still the same error.

select convert(smalldatetime, '2021-02-23T06:58:51') > convert(smalldatetime, GETDATE())

Started executing query at Line 1
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '>'.
Total execution time: 00:00:00.040

Upvotes: 0

Views: 216

Answers (2)

Thom A
Thom A

Reputation: 95544

As I said in the comments, columns need to be defined as a scalar expression. The expression you have is not a scalar expression, it is a boolean expression:

convert(smalldatetime, '2021-02-23T06:58:51') > convert(smalldatetime, GETDATE())

This doesn't tell SQL Server what to display, and would be an expression you would normally find in the WHERE. I.e. Display rows where the value of {column} is greater than the current date and time.

What you likely want is a CASE expression or IIF:

SELECT CASE WHEN '2021-02-23T06:58:51' > GETDATE() THEN 1 END 0 END;
SELECT IIF('2021-02-23T06:58:51' > GETDATE(),1,0);

Upvotes: 2

perry147
perry147

Reputation: 197

Is this what you want?

select IIF(convert(smalldatetime, '2021-02-23T06:58:51') > convert(smalldatetime, GETDATE()), 'True','False')

Upvotes: 1

Related Questions