SQL Server - Compare dates or datetime stored as a

2019-09-02 00:43发布

I made a date according to the datetime format. But, I stored this in my DB as a string/nvarchar and not a datetime. Will I be able to compare such dates ? Is this a bad practice ?

I am using nvarchar to store a datetime as of now.

2条回答
成全新的幸福
2楼-- · 2019-09-02 00:45

You will have to use either cast or convert to parse a datetime from the strings or compare the raw strings directly. The latter is possible depending on what format the strings are stored as. For example, if dates were stored in the format 'YYYYMMDD' you could simply compare string1 < string2.

查看更多
对你真心纯属浪费
3楼-- · 2019-09-02 00:52

Yes you can still be able to compare them but this is certainly a bad practice because you will need to convert this strings into dates data type to be able to compare between them. If you have indexes define on the column, they will not be used anymore since the column will be converted and it will cuase slow performance on large database.

An example on comparing dates is like this:

SELECT *
FROM   tableName
WHERE  CONVERT(DATETIME, dateSTRColumn, XXX) > GETDATE()

where XXX is the current format of the date stored as string.

查看更多
登录 后发表回答