0

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

4
  • you need to post the format in which the date is stored Commented Aug 31, 2016 at 19:08
  • I edited the question by adding the format. Commented Aug 31, 2016 at 19:09
  • You need to use Convert() to convert your varchar to a datetime Commented Aug 31, 2016 at 19:10
  • 1
    Why are you using the wrong data type? This is like asking how to clean the floor with a toothbrush rather than buying a mop. Commented Aug 31, 2016 at 19:29

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Based on the previous answer you need to convert the column convert(datetime, MessageTimestamp) >= @firstdate
That is correct I updated my answer. It's the column containing the varchar data that needs to be converted in order to be compared to time data types.
Thanks this is working, just one thing, for another table I see the date is saved as "19/05/2016 11:52:03 AM" and casting is not working for it. Any suggestion?
just a note: convert(datetime,@date,103) worked for the other. thanks
@ErayBalkanli it should work with convert. SELECT convert(datetime, '19/05/2016 11:52:03 AM', 103)
1

Try with the below code.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.