UPDATE each item in a column - sql

I'm having trouble figuring out a solution to this. I have several tables in my database with attributes having a date type. However, in one of my tables I was not thinking during the design process so the attribute is not of date but is a varchar. The dates in the "incorrect" table is formatted as dd-MMM-yyyy whereas all of the other dates are formatted as yyyy-mm-dd.
How can I run through the "incorrect" column and do CAST(myDate AS date) on each mis-typed attribute?

I'd migrate to a date column.
Add a nullable date column
Run an update query to set the value of each column to the result of your cast
Drop the varchar column
Refactor your code or rename the new column to the name of the old one

Related

Converting all data in a Varchar column to a date format

I'm working on a table with a column, 'Expiry Date', as a varchar with all data formatted as DD/MM/YYYY.
The creator of the table has used the wrong type for this expiry date column and now the client needs to filter and show all records before and after the current date as the time. This means the type needs to be changed to date or datetime type to be able to use the CURDATE() function.
However, the current format of the values does not satisfy and wont allow the type to change unless the format is changed to YYYY-MM-DD (or similar).
Is there any way to mass format the values in this column and this column alone as there are thousands of entries and formatting one by one would be extremely time consuming.
Let me assume that you are using MySQL.
Perhaps the simplest method is to add a generated column that is a date:
alter table t add column expiry_date_date as
(str_to_date(expiry_date, '%d/%m/%Y'));
You can also fix the data:
update t
set expiry_date = str_to_date(expiry_date, '%d/%m/%Y');
This will implicitly convert the result of str_to_date() to a date, which will be in the YYYY-MM-DD format.
More importantly, you can then do:
alter table t modify column expiry_date date;
Here is a db<>fiddle.
You can do similar operations in other databases, but the exact code is a bit different.
What you need is an update on that column, but before doing it I suggest you to check if the result is what you want.
select replace(expiry_date, '/', '-') new_expiry_date
from table_name
If this returns the results you want you can run the following update:
update table_name
set expiry_date = replace(expiry_date, '/', '-')
Of course you will need to replace expiry_date and table_name with the names of your column and table.

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

I have 3 tables in the database that I'm working on. Out of 3, two of the tables have columns that include dates. When I checked the information schema of the columns I found that dates have the wrong data type. If you see the picture below, the highlighted columns should be stored as DATE data type.
So, I used the following query to change their data type from varchar to DATE:
ALTER TABLE [dbo].[Customer]
ALTER COLUMN DOB DATE;
ALTER TABLE [dbo].[Transactions]
ALTER COLUMN tran_date DATE;
The error that I get is:
Conversion failed when converting date and/or time from character string.
Please let me know how I can fix this error. Thanks!
What you can do is update the value using try_convert() first and then alter the column name. Note: This will set any invalid values to NULL.
update customer
set dob = try_convert(date, dob);
alter table customer alter column dbo date;
If you want to see the bad values, then before you change the table, run:
select c.*
from customer c
where try_convert(date, dob) is null and dob is not null;
You may have other ideas on how to fix the values.
You can't change from varchar to date or time or datetime by altering the column. Why? Because SQL Server does not know if the field contains '1/1/2020' or 'My dog is cute'. You will have to rebuild the table with the proper data types and then CAST() or CONVERT() the values to a true date time.
Underneath the hood, this makes more sense. A char/varchar uses one byte per character. nchar/nvarchar uses 2 bytes per character. A datetime is a number, not a character. This means you need a routine that changes this into the correct number. If you want to get deeper, the number is the number of ticks (nanoseconds) since midnight on January 1, 0001 in the Gregorian Calendar. More info.

SQL convert varchar into Date

A long time ago I created a database, and completely forgot to set the column to Date and now looking at the data, I want to extract, it looks like 2006-05-06.
How would I run a SQL statement to convert it into the correct format (dd/MM/yyyy) 06/05/2006, I'm running with the British format "103".
What I was planning on doing, I've already added a second column (s_batch_convert2) to the database, hoping to convert into that and then delete the original column (s_batch_convert), renaming the new column to the old one.
UPDATE s_service_repairs
SET s_batch_convert2 = TRY_CONVERT(Date, s_batch_convert, 103)
Am I along the right lines?
You should convert your existing column to a bona fide date. It seems to have the right format:
alter table s_service_repairs alter column s_batch_convert date;
Then you can add a computed column for the format you want:
alter table s_service_repairs s_batch_convert_mmddyyyy as ( try_convert(varchar(10), s_batch_convert, 103) );

QMF query about date format

I have one column with the date format of yyyy-mm-dd and another with the format of mm/dd/yyyy. How can I change the second format to look like the first in QMF sql writing?
You can alter your table columns using an SQL command like this. I have specifically changed the column to a date format in the example
ALTER TABLE 'Schema_Name'.'Table_Name'
CHANGE COLUMN 'Column_Name' 'New_Column_Name' DATE NULL DEFAULT NULL;

How to sort by varchar field containing a date in ascending order [duplicate]

This question already has answers here:
Comparing dates stored as varchar
(3 answers)
Closed 3 years ago.
In design time we have given [DOJInGovrService] field as varchar datatype.
now when we are trying order by this parameter(DOJInGovrService) in ascending order it is not giving the desired result.
I know it is datatype problem but I can't change the datatype now as data is already entered.
SELECT ED.class,
ED.CurrentOfficePlace,
ED.DOB,
ED.DOJInCurrentOff,
ED.DOJInGovrService,
ED.DOJInSamvarg,
ED.EmpName,
ED.HomePlace, ED.Qualification
FROM tbl_EmplyeesBiodata ED
ORDER BY DOJInGovrService asc
Date entered is in format dd-MM-yyyy (i.e. 28-08-2004).
please help me
This is just one of many reasons why you should Always use appropriate data types.
Even when you have data in the table, you can change the data type using an alter table ddl statement:
ALTER TABLE tableName
ALTER COLUMN ColumnName datetime2;
However, you should copy this table first and try the alter on the copy, so that if it messes up your data you will not risk anything.
If the alter is successful then do it on your live table. if not, you can go with a different approach, involving these stages:
rename the DOJInGovrService column to DOJInGovrService_old. use sp_RENAME.
Add a column DOJInGovrService with the correct datatype (datetime2), using alter table ddl stement.
Update the new DOJInGovrService column with the values in DOJInGovrService_old. you will probably need to use convert.
drop the DOJInGovrService_old column using the alter table ddl statement.
Try to convert it to datetime
select ED.class,ED.CurrentOfficePlace,ED.DOB,ED.DOJInCurrentOff,ED.DOJInGovrService,ED.DOJInSamvarg,ED.EmpName,ED.HomePlace,ED.Qualification
from tbl_EmplyeesBiodata ED
order by convert(date,DOJInGovrService,105) asc
This is only direct solution. The best way to do that is create new column with date type. The column will helps you to create query without cast or convert.