Eray Balkanli
Eray Balkanli

Reputation: 7960

How to get data between two dates where the date column is varchar in SQL Server

I have a table in SQL Server 2008 with a MessageTimestamp column of type varchar(50) instead of datetime. I would like to get data from this table between two dates.

Normally, if the column was datetime, I would use a query like:

select * 
from myTable
where MessageTimestamp >= @firstDate and MessageTimestamp <= @lastDate

However, I cannot use this right now since this is varchar. I need a way as easy as possible to get those data rather than updating the column type. Any suggestion would be appreciated.

Edit: example date format stored -> 2016-05-16 11:20:00 AM

Upvotes: 0

Views: 1767

Answers (2)

Ola Ekdahl
Ola Ekdahl

Reputation: 1514

Use the CONVERT or CAST function. CONVERT(datetime, MesssageTimestamp) for example.

Upvotes: 1

Unnikrishnan R
Unnikrishnan R

Reputation: 5031

Try with the below code.

    Select * from myTable
     where cast(MessageTimestamp as datetime )>= @firstDate and cast(MessageTimestamp as datetime) <= @lastDate

Upvotes: 1

Related Questions