Copy varchar column data to date column - sql-server

I am using SQL Server 2017 and I have a table with a column of varchar type but the value is a date, i.e 'dd/mm/yyyy', and I need to convert this to a date value column.
I attempted a straight ALTER TABLE ALTER COLUMN like this:
USE <databasename>
ALTER TABLE <the_table_name>
ALTER COLUMN [column name] date;
GO
But the output is an error
Conversion failed when converting date and/or time from character string
I added a new column [AltColumnName] with the intention of copying over the column values with an UPDATE statement, and then renaming the columns but so far all forms of UPDATE I try fails with the same "conversion failed" message.
How do I copy over the varchar column values to the date column?

Assuming that all rows are dd/MM/yyyy and are valid.
First you need to change your value to an ISO format, we're going to use yyyyMMdd
UPDATE dbo.YourTable
SET DateColumn = CONVERT(varchar(10),CONVERT(date,DateColumn,103),112);
Then you can ALTER your table:
ALTER dbo.YourTable ALTER COLUMN DateColumn date;

Related

Converting varchar date field to datetime datatype [duplicate]

This question already has answers here:
Is there a way to convert a varchar to DATETIME in SQL SERVER 2008?
(4 answers)
Closed 2 years ago.
I made the mistake of using varchar to store my data that represents date/time. Now I'm trying to convert my column of text data, stored as a varchar, like so:
2020-11-25T14:22:41.3539327Z
Into a column that stores a datetime datatype.
Provided that all your data is in the format yyyy-MM-ddThh:mm:ss.nnnnnnn then you can just change the data type of the column:
ALTER TABLE dbo.YourTABLE ALTER COLUMN YourColumn datetime2(7);
If you need the timezone in there, then use datetimeoffset(7) instead.
-- to fix it you can use convert, below uses GetDate for examaple
SELECT convert(varchar, getdate(), 120)
depending on what precision you need you can use the link below to find it and change the 120 to whatever number you need for that precision.
https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
To fix your table you should follow these steps:
Add a new column to your table for DateTime
Run an update on your table using the Convert above to update the new column with the converted value from your varchar field.
Then drop the column with the varchar data.
Code to do the steps I outlined above
ALTER TABLE dbo.TableName ADD NewDateTimeCOL DATETIME
-- NOTE if your table is LARGE you will not want to do a direct update like this but do looping for performace purposes
UPDATE dbo.TableName
SET NewDateTimeCOL = convert(varchar, OldDateTimeCOL, 120)
ALTER TABLE dbo.TableName DROP COLUMN OldDateTimeCOL

How to change datatype VARCHAR to DATETIME?

My current Database column's datatype is varchar, but I want to alter it to datetime. I use this sqlserver code to alter it, but failed.
ALTER TABLE Logbook
ALTER COLUMN Company_Date datetime NOT NULL;
Result:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
The easiest option here might be to use TRY_CONVERT:
ALTER TABLE Logbook ADD COLUMN Company_Date1 datetime;
UPDATE Logbook
SET Company_Date1 = TRY_CONVERT(datetime, Company_Date);
ALTER TABLE Logbook DROP COLUMN Company_Date;
sp_rename 'Logbook.Company_Date1', 'Company_Date', 'COLUMN';
The strategy here is to create a new datetime column Company_Date1 which is a bona fide datetime column. Then, we update it using TRY_CONVERT against the text values in Company_Date. Note that should the conversion not be possible, there would be no error, but instead a NULL would be returned. Finally we drop the original text Company_Date column and rename Company_Date1 to Company_Date.
you have some bad data in column one way you can use isdate function before alter column such as
update logbook set company_date=null where isdate(company_date)=0
after that alter column
another way select the list of bad data and correct it then alter column

Unable to change varchar column to date type

I have a table in my SQL Server 2017 database that contains a varchar(10) column whose values all conform precisely to date. Here are some sample values, but there are many more:
2014-06-30
2004-05-06
2014-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06
2009-06-30
2001-08-18
2004-05-06
I am trying to convert this column to a date:
alter table SourceTable1 alter column END_DATE date;
...but I always get this error:
Conversion failed when converting date and/or time from character
string.
I have examined the data and 100% of the column values conform to the date type. How can I change the column to date type?
I did a simple test and it worked:
create table #t (t varchar(10))
insert into #t values ('2001-08-18')
alter table #t alter column t date
Another with something that looks like date but it isn't (got the same error as you):
create table #tt (t varchar(10))
insert into #tt values ('2001-08-32')
alter table #tt alter column t date
For sure you have a row that contains a varchar(10) that is not convertable. You can find this values by using a select like this:
select try_cast(yourColumn as date) as tryCastyourColumn, yourColumn
from Yourtable
where try_cast(yourColumn as date) is null
I agree with M. Kanarkowski that your examples seem fine, but you probably are missing something. Since you have the 2017 version, run this to check what's wrong:
select END_DATE
from SourceTable1
where END_DATE is not null and try_convert(date,END_DATE) is null

I need to update my table by converting a column from int into date in sql server

I want to update the column transe_date from int into date ..
update fci
set fci.transe_date= convert(date,convert(varchar(8),transe_date));
Rather than creating a new column, completing an UPDATE statement, renaming your old column, and then the new, you could use 2 ALTER statements. You can't implicity convert an int to date, but you can implicitly convert an int to varchar and then from a varchar to a date:
USE Sandbox;
GO
CREATE TABLE dbo.SomeTable (DateColumn int);
INSERT INTO dbo.SomeTable (DateColumn)
VALUES (20160101),
(20160307),
(20180920);
GO
SELECT *
FROM dbo.SomeTable
GO
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn varchar(8);
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn date;
GO
SELECT *
FROM dbo.SomeTable
GO
DROP TABLE dbo.SomeTable
Of course, this assumes that all your ints are valid date values.
Edit: If you do have values that aren't valid date values, you'll need to identify and correct these first. You could identify these by using TRY_CONVERT:
SELECT YourIntColumn
FROM dbo.YourTable
WHERE TRY_CONVERT(date,CONVERT(varchar(11),YourIntColumn)) IS NULL;
There's no need to put a TRY_CONVERT on the varchar(11), as an int can always be converted to a varchar. I used varchar(11) as well (instead of varchar(8)( because the largest value, in character length, you could have would be -2147483648 (which is 11 characters long).
Make a dummy column to hold data
Change data type of existing column
put all values back after converting using the column made
Drop the dummy column
Cleaning the new column
Script sample will be
/*1*/
Alter Table FCI
Add tempcol DateTime
Go
/*2*/
update fci
set tempcol = convert(date,convert(varchar(8),transe_date));
/*3*/
Alter Table FCI
alter column transe_date DateTime
Go
/*4*/
update fci
set transe_date = tempcol;
/*5*/
Alter Table FCI
drop column tempcol
Go
If the whole data is Date then directly converting the column type can do the job, the above process is the safe side process for start.
If you want to convert the int values into dates, you will first have to add a new column (transe_date2) of that type. Then, you can store the converted values in this new column:
update fci
set fci.transe_date2 = convert(date,convert(varchar(8),transe_date));
Having done this, I suggest to use SSMS to drop the old column and rename the new one.
Here are the steps:
--add date column
ALTER TABLE fci ADD transe_date2 date;
GO
--do conversions
UPDATE fci SET transe_date2=CONVERT(date,CONVERT(varchar(8),transe_date),112);
GO
--drop int column
ALTER TABLE fci DROP COLUMN transe_date;
GO
--rename temporary column to transe_date
EXEC sp_rename 'fci.transe_date2', 'transe_date', 'COLUMN';

Convert varchar to numeric in vertica

Is It possible to change varchar(10) column to data type numeric(10,4) using alter statement.
I tried it with alter command but getting an arror:
cannot convert column from varchar(10) to numeric(10,4)
You can't convert directly from VARCHAR to a numeric type, but you can work around the restriction by creating a temporary (numeric) column, populating it based on the current column, and then renaming it. When populating it, you'll need to make sure that the value is actually a number, for example that it does not contain commas as separators, punctuation like $, etc.
The documentation gives this example, where the original price column has values like '$50.00':
ALTER TABLE sales ADD COLUMN temp_price NUMERIC(10,2) DEFAULT
SUBSTR(sales.price, 2)::NUMERIC;
ALTER TABLE sales ALTER COLUMN temp_price DROP DEFAULT;
SELECT MAKE_AHM_NOW();
ALTER TABLE sales DROP COLUMN price CASCADE;
ALTER TABLE sales RENAME COLUMN temp_price to price;

Resources