sequel.learner
sequel.learner

Reputation: 3951

SQL Server - Compare dates or datetime stored as a string or nvarchar?

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.

Upvotes: 1

Views: 7743

Answers (2)

John Woo
John Woo

Reputation: 263723

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.

Upvotes: 2

user1172023
user1172023

Reputation:

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.

Upvotes: 1

Related Questions