Bobski Bobski - 1 year ago 64
SQL Question

Querying dates in SQL Server

I have some dates saved as

. 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
. Can someone help?

This is what I've been trying...

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

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

Select * from tblAd1
order by date1

Answer Source

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