Bobski Bobski - 2 months ago 15
SQL Question

Querying dates in SQL Server

I have some dates saved as

VARCHAR(25)
. I'm trying to write a query to search for Date1 but it's not doing it simply because the date is not saved as
DATE
or
DATETIME
. Can someone help?

This is what I've been trying...

Select * from tblAd1
where date1 = '9/12/2016'


EDIT:
My mistake - it was happening when I tried to do
ORDER BY
Date1 is when it wasn't doing it properly.

Select * from tblAd1
order by date1

Answer

Use CAST or Convert

Select * 
from tblAd1
where cast(date1 as date) = '2016-09-12'

Even though it possible to search, you should store dates in DATE datatype rather storing in Varchar. Since you are storing date in varchar type there are more changes to store bad dates which leads to error when converting it to date. Also this avoid usage of any index present in date1 column