SQL convert varchar into Date - sql

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) );

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.

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;

converting varchar to date format in sql server

I have a table with two date column. However the columns are in varchar. I need to covert them as date format.
The sample data is like this:
Account Number | Registration Date | System Status Change Date
01740567715 | 10-JUL-13 | 30-JUL-13 12.53.32.000000000 PM
I want both of these columns like this: 10-Jul-2013.
For Registration Date, I am using this code:
Update [dbo].[SysDataV2]
Set ["REGISTRATION_DATE"]= convert(datetime, (["REGISTRATION_DATE"]), 106)
But it is shwoing the result as varchar and also showing erroneous format.
For System Status Change Date I am using following code:
update [dbo].[SysData]
Set ["KYC_STATUS_CHANGED_DATE"]= REPLACE(CONVERT(datetime,convert(datetime,left(["KYC_STATUS_CHANGED_DATE"],9),103),106),' ' ,'-')
Both are changing to date format of some type (not my expected format) but in table structure they are still shown as varchar.
What am I doing wrong here?
The table's data type is still varchar. An update merely changes the string, it doesn't change the data type. What you should do is (assuming all of the dates are valid and this format is 100% consistent):
UPDATE dbo.SysData SET REGISTRATION_DATE =
CONVERT(CHAR(10), CONVERT(DATE, REGISTRATION_DATE, 106), 120);
UPDATE dbo.SysData SET KYC_STATUS_CHANGED_DATE =
CONVERT(CHAR(10), CONVERT(DATETIME, LEFT(KYC_STATUS_CHANGED_DATE, 9), 106), 120)
+ REPLACE(SUBSTRING(KYC_STATUS_CHANGED_DATE, 10, 9), '.',':')
+ RIGHT(KYC_STATUS_CHANGED_DATE, 2);
ALTER TABLE dbo.SysData ALTER COLUMN REGISTRATION_DATE DATE;
ALTER TABLE dbo.SysData ALTER COLUMN KYC_STATUS_CHANGED_DATE DATETIME;
And then stop inserting regional and potentially problematic strings. String literals representing dates / datetimes should be:
-- date only
YYYYMMDD
-- with time:
YYYY-MM-DDThh:mm:ss.nnn
But best is to simply make sure they are date or datetime values before you ever hand them off to SQL Server. Your application should be able to do this without ever converting to some arbitrary string format. Never, ever, ever store date or datetime values as strings in SQL Server. You gain nothing and you lose quite a lot.
You need to change the data type of the column from a varchar to store it as a Date. Then when you select it you can format it any way that you like. One way to do this would be to create a new column of the correct datatype and convert the data, then remove the old column. Make sure the the old column doesn't have and foreign key relationships or you will also need to transfer those over as well.
ALTER TABLE [dbo].[SysData] ADD ConvertedDate DateTime
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as DateTime)
ALTER TABLE [dbo].[SysData] DROP COLUMN VarCharDate

UPDATE each item in a column

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