Comparing dates stored as varchar

后端 未结 3 2064
栀梦
栀梦 2020-12-02 01:44

I need to compare dates that are stored in my database as varchar against today\'s date.

Specifically, I need to exclude any records with a date that has passed.

3条回答
  •  清歌不尽
    2020-12-02 02:03

    If you HAVE TO store your dates as varchar (and as per other other answers, this is a poor practice), then using an ISO style format like yyyy-mm-dd should allow textual comparisons without issue. If your column is a date data type, and you're using SQL 2012 or later then use DATEFROMPARTS (or one of its variants) for date comparison, so

    WHERE DateToCompare < DATEFROMPARTS (2019, 12, 31)
    

    rather than

    WHERE DateToCompare < '2019-12-31'
    

    SQL handles the latter fine, but the former is more "correct".

提交回复
热议问题