Alter nvarchar column type to datetime - sql

ALTER TABLE table_name
ALTER COLUMN columnWithDate datetime;
columnWithDate is a type of nvarchar(255), data are in 2018.06.19. form. I've checked all distinct values and there are one row with NULL value in columnWithDate.
I get the following error runninf the alter command:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
What am I missing here?

You need to first change your values to a unambiguous format and then change the datatype. For the value you have that would be simply removing the ., as that produces the ISO format yyyyMMdd:
UPDATE YourTable
SET YourDateColumn = REPLACE(YourDateColumn,'.','');
ALTER TABLE YourTable ALTER COLUMN YourDateColumn datetime; --Should this not be a date?
As I comment though, date would likely be a better choice here, as you have no time portion in your value(s).

I suspect the extra dot(.) after the date is the culprit. In your example 2018.06.19.
This below snippet giving me the same error
DECLARE #DATE NVARCHAR(255)= N'2018.06.19.'
SELECT CAST(#DATE AS datetime)
Msg 242, Level 16, State 3, Line 3 The conversion of a nvarchar data
type to a datetime data type resulted in an out-of-range value.
So just remove the dot from the nvarchar field befor Alter.

The value is not correct somewhere in the column. I would suggest finding it:
select columnWithDate
from table_name
where try_convert(datetime, columnWithDate) is null and
columnWithDate is not null;
If you want to remove incorrect dates, then update first:
update table_name
set columnWithDate = try_convert(datetime, columnWithDate);
This converts the value back to a string, but the string should be convertible on your system right back to a datetime.

Related

Converting date format gives "Conversion failed when converting date and/or time from character string"

The date format in the table is YYYYMMDD and I would like to convert it to the following format but it is failing with an error:
2019-07-23 00:00:00.000
Conversion failed when converting date and/or time from character string
Here is the statement I'm using:
convert(varchar(10), convert(datetime, InstallDate0), 23)
The real problem is the choice of your datatype. varchar is the wrong choice. As a result, it seems that you now have some rows where the value of the "date" has been lost, as it can't be converted to a date.
To properly fix this problem, fix your datatype. Firstly I would create a new column to store the bad values:
ALTER TABLE YourTable ADD BadDate varchar(20); --as it's yyyyMMdd you don't need more than 8 characters, but we'll assume you have some really bad values
UPDATE YourTable
SET BadDate = InstallDate0
WHERE TRY_CONVERT(datetime,InstallDate0) IS NULL;
Now that you've done that, time to update the existing column:
UPDATE YourTable
SET InstallDate0 = CONVERT(varchar(8),TRY_CONVERT(datetime, InstallDate),112);
This'll set every value to the yyyyMMdd format where the value can be converted. NOw you can alter your table:
ALTER TABLE YourTable ALTER COLUMN InstallDate0 date; --AS it's yyyyMMdd, it seems silly to actually use datetime
Now you have a proper datetime column.
You'll then need to inspect the values of BadDate and try to correct them (or admit that any information they held has been lost for ever).
If you "must" have another column with the format, then add a further column:
ALTER TABLE YourTable ADD InstallDate0_f AS CONVERT(varchar(23),InstallDate0,121);
You can determine where the problems are using TRY_CONVERT(). The problem would seem to be the conversion to a datetime, so try this:
select InstallDate0
from t
where try_convert(datetime, InstallDate0) is null;

SQL Server: best way to insert "mm/dd/yyyy" into a "date" or "datatime2" column?

I have a bunch of values in the form of mm/dd/yyyy stored in a CSV. An example is 06/26/2017. What I found was that I could NOT insert it into a column declared as date or datetime2 type. What I CAN do is to modify that (empty) column to varchar first, then insert.
However at this point, after insertion as varchars, how can I convert this column to "date" or "datatime2"?
Attempting to set system-wide format doesn't work:
sql> SET DATEFORMAT 'mm/dd/yyyy'
[2019-03-31 09:42:04] [S0001][2741] SET DATEFORMAT date order 'mm/dd/yyyy' is invalid.
If the column's data type is date then convert the string to date with:
convert(date, '03/31/2019', 101)
and then insert it.
See the demo.
Read more about convert()
Edit:
Create a varchar column and a date column. Insert the values inside the varchar column and when the process finishes, update the date column by converting each value to a date, like:
UPDATE tablename
SET datecolumn = convert(date, varcharcolumn, 101)
After that you can remove the varchar column.

sql type conversion

I have a column datedocumented in the format YYYYMMDD and of the datatype nvarchar. I want to change the data type to datetime and update the column name exdatedocumented and alter the table using ALTER .can anyone help in this.I have tried something like this
update dbo.table2
set [DateDocumented] = convert(datetime,CAST([DateDocumented] as datetime),130)
I ended up getting error
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated
.
You should be able to just change the column type:
alter dbo.table2 alter column DateDocumented datetime;
Your column is in a format suitable for conversion. If you wanted to use default formats instead, just do:
update table dbo.table2
set [DateDocumented] = convert(datetime, CAST([DateDocumented] as datetime));
This should also allow the column to be converted to a datetime.
1st change that column name then alter table
sp_RENAME 'dbo.table2.datedocumented', 'exdatedocumented' , 'COLUMN'
go
ALTER TABLE dbo.table2
ALTER COLUMN exdatedocumented datetime;
It seems we have two things going on here. Changing the type for a column. And changing the name for a column. Let's try to keep these separate so not to confuse things. I will adress the changing of type (from varchar to datetime):
First of all: Why datetime? Why note datetime2 (with whatever fractions of seconds you want, for instance datetime2(0))? The new types for date and time has been around for 10 years now!
Anyhow, you apparently have values in your table which are not valid dates! First thing you need to do is to find those rows and handle them. Lets say that you will change to datetime2(0), if not, then just change below to datetime instead:
SELECT *
FROM dbo.Table2
WHERE TRY_CAST(DateDocumented AS datetime2(0)) IS NULL

Converting varchar datatype to datetime datatype using SQL 2012 management studio

I have a column which has ddmmmyyyy:hh:mm:ss.nnnnnn it is stored as varchar(25). I need to save it as datetime in the same column. I have tried using
update tablename
set columnname = (SUBSTRING(columnname,1,2) + '-' + SUBSTRING(columnname,3,3) + '-' +
SUBSTRING(columnname,6,4) + ' ' + SUBSTRING(columnname,11,8));
and then
alter table tablename
alter columnname datetime;
but later it shows up the error
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
How do I change it any other opinion or any modification for the above query. Please help. Thank you.
As per your given string format, you should use datetime2 data type
Your string format is almost correct, only 1 colon is extra after Year.
If you fix that thing, you can directly cast the varchar field into datetime2. For example first you can replace the extra colon with space by running following query,
UPDATE myTable
SET targetColumn = STUFF ( targetColumn , 10, 1, ' ')
-- ddmmmyyyy:hh:mm:ss.nnnnnn
-- \
-- this colon is extra which is at 10th position
After this you can directly ALTER your table and change the data type to datetime2.
Important: data in all the lines must contain valid date
Here is a test which shows how you can convert
CREATE TABLE testTable(testCol varchar(25));
INSERT INTO testTable(testCol)
VALUES('03Jan2014 18:33:39.999999');
ALTER TABLE testTable ALTER COLUMN testCol datetime2;
SELECT *
FROM testTable
DROP TABLE testTable;
It has already been answered here: Is there a way to convert a varchar to DATETIME in SQL SERVER 2008?
He uses: convert(datetime,'24/05/2012 09:56:06',103)
Although you might have to do some substrings to adapt to a format covered by convert: http://www.sql-server-helper.com/tips/date-formats.aspx
Add a new column
alter table t
add n datetime
Update the new column
update t
set n = datetimefromparts(
cast(substring(o,6,4) as int),
case substring(o,3,3)
when 'jan' then 1
...
when 'dec' then 12
end,
cast(substring(o,1,2) as int),
cast(substring(o,11,2) as int),
cast(substring(o,14,2) as int),
cast(substring(o,17,2) as int),
cast(substring(o,20,6) as int)
)
If you need to drop the old column
alter table t
drop column o

Converting Varchar into Date in data type

I am relatively new to SQL Server so I was wondering how to convert the data type from varchar to date format? I have a few thousands records so I need a query to help to convert the varchar to date in a single query.
I have the date in this format: yyyymmdd, in varchar(8) and I want to convert this into yyyymmdd, in date format.
Is there any queries to help me with this?
For various conversions between VARCHAR and DATETIME have a look at this link.
Actually in your case, since your VARCHAR is in yyyymmdd format, you could just:
convert(datetime, YourVarcharDateField, 112)
Simply Use this Inbuilt CONVERT Function, and Check this Link for formatting Dates
-- Use 101 if you have divider in your date
SELECT convert(datetime, '2014-01-02',101) as [DateTime]
-- Use 112 if you don't have divider in your date
SELECT convert(datetime, '20140131',112) as [DateTime]
Edited:
UPDATE yourTable SET field = convert(datetime, 'yourFieldName',112)
--This will update all of your field regardless of any particular row
--If you want to update any particular set of rows use `WHERE` clause
if you have more various formats goto to the given link.
Data types can be converted either implicitly or explicitly.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
Explicit conversions use the CAST or CONVERT functions.
The CAST and CONVERT functions convert a value (a local variable, a column, or another expression) from one data type to another
convert(datetime, '2013-05-04',101)
CAST ( expression AS data_type )
ALTER TABLE [dbo].[table] ADD ConvertedDate Date
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as Date)
ALTER TABLE [dbo].[table] DROP COLUMN VarCharDate
Use CAST OR CONVERT function to convert string to date
Try this:
SELECT CAST('20140102' AS DATE) AS convertedDate;
SELECT CAST(colName AS DATE) AS convertedDate FROM tableA; -- Replace column name and table name
OR
SELECT CONVERT(DATE, '20140102', 112) AS convertedDate;
SELECT CONVERT(DATE, colName, 112) AS convertedDate FROM tableA; -- Replace column name and table name
OUTPUT of both queries:
|convertedDate|
|-------------|
|2014-01-02 |
In SQL SERVER, there are two types of built in conversion techniques.
Convert
Cast
Convert having its own defaults so it will be outdated in upgraded version of SQL SERVER
better make use of CAST Conversion technique
In your scenario.Already having the date with datatype of Varchar(8) trying to Convert into Date
Solve in systematic manner.
Adding the one new Column in the existing table.
Alter Table Table_name Add changedDataTypeDate Date
Update the values in varchar datatype to Date Datatype
UpDate Table_name Set ChangedDataTypeDate = CAST(OriginalDataTypeDate as Date)
Again change the new column name into old column name.
Sp_Rename 'Tablename.changedDataTypeDate','OriginalDataTypeDate','COLUMN'
Its done.
Based on u r requirement.
Alter Table customer Add Purchase_Changedtype Date
Update Customer set Purchase_changedtype = CAST(Purchase_date as Date)
(If u need Time also replace Datetime istead of Date)
Alter table Customer Drop column Purchase_date
Sp_Rename 'Customer.Purchase_ChangedType','Purchase_Date','Column'