1
votes

I want to covert varchar (50) column to date format. I used following code:

Update [dbo].[KYCStatus062013] 
Set [REGISTRATION_DATE_]= convert(datetime,[REGISTRATION_DATE_] ,103)

But there is an error that says:

Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.

I want this format: dd-mmm-yyyy. I do not have any option to create another table / column so "update" is the only way I can use. Any help will be highly appreciated.

Edit: my source data looks like this:

21-MAR-13 07.58.42.870146 PM  
01-APR-13 01.46.47.305114 PM  
04-MAR-13 11.44.20.421441 AM  
24-FEB-13 10.28.59.493652 AM

Edit 2: some of my source data also contains erroneous data containing only time. Example:

 12:02:24
 12:54:14
 12:45:31
 12:47:22
3
Show us some sample data of the column in question.Adriaan Stander
you are trying to update column REGISTRATION_DATE_ on the same column converted to datetime.Roman Pekar
@RomanPekar that doesn't seems to be the problem, since the target column is varcharLuis LL

3 Answers

2
votes

Try this one.

Update [dbo].[KYCStatus062013] 
Set [REGISTRATION_DATE_]= REPLACE(CONVERT(VARCHAR(11),[REGISTRATION_DATE_],106),' ' ,'-')

this will give output as dd-mmm-yyyy

if you want to update as date format then you have to modify your table.

Edit 1 =

Update [dbo].[KYCStatus062013] 
    Set [REGISTRATION_DATE_]= REPLACE(CONVERT(VARCHAR(11),convert(datetime,left([REGISTRATION_DATE_],9),103),106),' ' ,'-')

Edit 2 = Check this

http://sqlfiddle.com/#!3/d9e88/7

Edit 3 = Check this if you have only enter time

http://sqlfiddle.com/#!3/37828/12

1
votes

The error suggests that one of the values in your table does not match the 103 format and cannot be converted. You can use the ISDATE function to isolate the offending row. Ultimately the error means your table has bad data, which leads to my main concern. Why don't you use a datetime or date data type and use a conversion style when selecting the data out or even changing the presentation at the application layer? This will prevent issues like the one you have described from occurring.

I strongly recommend that you change the data type of the column to more accurately represent the data being stored.

0
votes

The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types.

to_date(text, text)
to_date('05 Dec 2000', 'DD Mon YYYY')

for further details here click

http://www.postgresql.org/docs/8.1/static/functions-formatting.html