Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am getting an error when converting a varchar column into a data column

I am using SQL Server.

I have a table with a column called [DateReceived]. Now the column is a ‘varchar’ column. The date format is: ’18/05/2022′. When I try to convert it to a ‘date’ column using:

ALTER TABLE Correspondence ALTER COLUMN [DateReceived] DATE;

I get the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Conversion failed when converting date and/or time from character
string.

>Solution :

You cannot simply convert a text date column to a bona fide date in this way. What you could do would be to create a new column and populate it using TRY_CONVERT:

ALTER TABLE Correspondence ADD DateReceivedNew Date;

Then, populate it using TRY_CONVERT:

UPDATE Correspondence
SET DateReceivedNew = TRY_CONVERT(date, DateReceived, 103);
-- note: use format mask 103 for dd/mm/yyyy

In the case of any error, your DateReceived column may have bad data in it. You may use the following query with TRY_CONVERT to flush out any offending records:

SELECT *
FROM Correspondence
WHERE TRY_CONVERT(date, DateReceived, 103) IS NULL;

Finally, you may drop the original DateReceived column, and rename DateReceivedNew:

ALTER TABLE Correspondence DROP COLUMN DateReceived;
sp_rename 'Correspondence.DateReceivedNew', 'DateReceived', 'COLUMN';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading