0

When using the below query the "Result_field" returns "NO" even if the date is greater than 12/31/2020. How can I get it to show "YES" when the date is greater than 12/31/2020 and "NO" When Less Than? Been trying to research this for a while and now need help. This may be a simple query, but I'm kinda new at this. Thanks in advance.

SELECT Date_field,
CASE 
    WHEN Date_field < '2020-12-31' THEN 'NO' ELSE 'YES'
    end as Result_field
FROM Yearly_Report;

This is the result I get:

Result Image

1
  • 3
    Is Date_field actually a string column? If so, why? Commented Jun 3, 2020 at 23:37

1 Answer 1

2

Without seeing the table definition, this is kind of an educated guess, but it looks like your Date_Field is a string field (VARCHAR, NVARCHAR etc) instead of a DATE or DATETIME field.

As per this fiddle, when defined as a VARCHAR field the results are all "NO" because the comparison is a string to string and doesn't make any sense (one string cannot be less than another string). When defined as a DATE field, the comparison value is implicitly converted to a DATE value and then can be successfully compared.

The correct solution would probably be to change the data type of the Date_Field column to DATE or DATETIME, however, if this isn't possible you can resolve this in the query alone using TRY_PARSE:

SELECT DateField,
CASE 
    WHEN TRY_PARSE(DateField AS DATE USING 'en-US') < '2020-12-31' THEN 'NO' ELSE 'YES'
    end as ResultField
FROM Dates;

You can see the results in the fiddle are as expected:

DateField   ResultField
-----------------------
06/30/2022  YES
06/30/2018  NO
12/31/2022  YES
06/30/2020  NO
09/30/2020  NO
03/31/2020  NO
03/31/2024  YES
06/30/2021  YES
6
  • DATE is deprecated --> what? Commented Jun 3, 2020 at 23:38
  • @AaronBertrand I thought I had read somewhere that the DATE data type was being deprecated, but I can't find the article any more. Updated the answer and removed this.
    – HandyD
    Commented Jun 3, 2020 at 23:41
  • @HandyD, that article was about datetime probably. There is a note in the docs.
    – i-one
    Commented Jun 4, 2020 at 11:21
  • @HandyD. Unfortunately the work around did not work for me. After trying I received an error. Msg 195, Level 15, State 10, Line 470 TRY_PARSE is not a recognized built-in function name. It looks like the Database compatibility is only 2008.
    – Calvin
    Commented Jun 4, 2020 at 14:27
  • I'm not the owner of the Database or Table creator. I'm only running a few reports and don't want to update the table. I do understand why it's not working on my end. If there are any other workaround I can use, please let me know.
    – Calvin
    Commented Jun 4, 2020 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.