1

I have a column which stores date in String format like (11/01/2010,2014-04-08,14-Oct-14).
I want to convert all this type of string dates in datetime/date format like (Dec 16 2014 3:40PM) I am trying like that

update #test set new_CHQ_DATE = CONVERT(varchar(20), CHQ_DATE, 105) where CHQ_DATE like  '__/__/____'
update #test set new_CHQ_DATE = CONVERT(varchar(20), CHQ_DATE, 105) where CHQ_DATE like  '____-__-__'
update #test set new_CHQ_DATE = CONVERT(varchar(20), CHQ_DATE, 105) where CHQ_DATE like  '__-___-__'

Bu

3
  • 3
    Um, it would be far better for you to store it as an actual DATE type. For one thing, your chosen format doesn't sort nicely, so it'd be useless to add that column to an index. Commented Dec 17, 2014 at 12:18
  • Before you convert your column to a varchar, you have to first convert it to a Date or Datetime. Converting a varchar to a varchar doesn't do anything. Commented Dec 17, 2014 at 14:28
  • 1
    You really should us the date(time) datatype for this. Leave the formatting to the front end where it belongs. Commented Dec 17, 2014 at 14:38

1 Answer 1

2

Your sample seems to work, although it relies on you knowing ahead of time all of the various different ways that people may have entered dates. SQL Server is pretty decent about converting strings into dates, if the string is in basically any NORMAL date recognizable format. This query seems to get more or less all of them (assuming that CHQ_DATE is some kind of VARCHAR and that new_CHQ_DATE is a DATETIME column):

SET DATEFORMAT dmy;
GO
UPDATE #Test
   SET new_CHQ_DATE = CONVERT(VARCHAR(20), CHQ_DATE, 105)
WHERE
   ISDATE(CHQ_DATE) = 1;

--reset DATEFORMAT back to whatever it was
Sign up to request clarification or add additional context in comments.

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.