SQL Server - Compare dates or datetime stored as a

2019-09-02 00:13发布

问题:

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.

回答1:

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.



回答2:

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.