1

I have a column of varchar type and it contains a lot of data (we are talking about millions of records). I select only the date columns, like this:

select Value from mytable where ISDATE(mytable.Value) = 1

and I want to convert all the values in the result to the format of MM/dd/yyyy HH:mm:ss tt

Note that the values are of many different formats.

How can I do that in SQL Server?

4
  • Do you know all of the possible date formats ahead of time? I'd think you need to parse all the strings into an intermediate DATETIME object and then pull the string back out using your display format. Commented Oct 14, 2012 at 20:04
  • Why not convert dates from the UI instead consuming DB Server resources? Commented Oct 14, 2012 at 20:24
  • @Ron, what kind of UI are you talking about? I have millions of already stored date values unfortunately stored as varchars and I want to convert them to a unified format. Commented Oct 14, 2012 at 20:27
  • Sorry, I didn't realize this was a permanent conversion. Commented Oct 14, 2012 at 22:00

1 Answer 1

1

Try this

SELECT CONVERT(VARCHAR(10), CAST(value as datetime), 101) + ' ' 
     + substring(convert(varchar(20), CAST(value as datetime), 9), 13, 5) 
     + ' ' + substring(convert(varchar(30), CAST(value as datetime), 9), 25, 2) As dateValue
FROM mytable 
WHERE ISDATE(mytable.Value) = 1

More on date formats for SQL SERVER

SQL Server Date Formats

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

6 Comments

@RichardTheKiwi Reason is that he needs it in "MM/dd/yyyy HH:mm:ss tt" Can you do you that without breaking day and time? Please, add your answer, if you can.
@RichardTheKiwi You've deleted your comment? What about downvote? Can you make your point?
thank you, I figured out the remaining of the solution myself independently from your answer, which is not the same, but it's equivalent, of course. Thank you again.
@Lajos Arpad , you're welcome. Please, add you answer too as answer or in your question, so that others can see solution.
It is equivalent to yours, there is no difference between the idea behind my solution and yours, so, basically I would duplicate your answer, as I started to solve the AM/PM problem based on your initial answer. There is no point really to put in my answer, because there are no relevant differences.
|

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.