This question already has answers here:
Conversion failed when converting date and/or time from character string while inserting datetime
(18 answers)
Closed 7 years ago.
I'm trying to update field (Type of Date) from a string field.
The string field example : 20/10/2015
I am new in sql. I tried this query:
UPDATE [dbo].[EmployeeWithCompCar]
SET [EMER_AttachEndDate] = cast([EMER_info1] as date)
I get this message:
Conversion failed when converting date and/or time from character string.
Can you help me fix it?
Thank's!
You need to use convert() with a format. So try this:
UPDATE [dbo].[EmployeeWithCompCar]
SET [EMER_AttachEndDate] = convert(date, [EMER_info1], 103);
The formats are available in the documentation.
Note: In SQL Server 2012+, use try_convert() instead of convert(). That way, if a string is in the wrong format, the result is NULL instead of an error.
You can use CONVERT with the format style 103.
UPDATE [DBO].[EMPLOYEEWITHCOMPCAR]
SET [EMER_ATTACHENDDATE] = CONVERT(DATE, [EMER_INFO1], 103)
And if you don't blank to be updated to 1900-01-01 you can use NULLIF function to avoid that.
UPDATE [DBO].[EMPLOYEEWITHCOMPCAR]
SET [EMER_ATTACHENDDATE] = CONVERT(DATE, NULLIF([EMER_INFO1], ''), 103)
Date Formats in SQL Server
NULLIF
Related
I'm using MS SQL server and I have a date field of type text. The dates stored there are in this format
2017-03-01T18:23:02+0700
I'm trying to convert this field in a datetime field but I fail. I have tried
CONVERT(datetimeoffset,date, 127)
CONVERT(datetime,date, 127)
CONVERT(datetime2,date, 127)
but I keep getting
Conversion failed when converting date and/or time from character
string.
I think the problem is that according to ISO8601 the time offset must be in the format hh:mm while mine is hhmm. I don't mind keeping only the date (yyyy-mm-dd) if it is more easy.
I have read similar question but none matches exactly my case and I can't figure out the solution.
Try this
Declare #dt varchar(50)
set #dt = '2017-03-01T18:23:02+0700'
select convert(datetime, replace(LEFT(#dt, LEN(#dt) - 1), '+', '.'), 126)
If you need only date part then you can use below query
SELECT CAST(LEFT('2017-03-01T18:23:02+0700',10) as DATE)
Use Below query to convert datetime :
SELECT CONVERT(DATETIME,REPLACE(REPLACE('2017-03-01T18:23:02+070','T','
'),'+','.'),103)
For DATE only use below query :
SELECT CONVERT(DATE,REPLACE(REPLACE('2017-03-01T18:23:02+010','T','
'),'+','.'),102)
It doesn't seem to work in both ways (both raise error):
SELECT CONVERT(datetime,'2017-03-01T18:23:02+0700',127)
SELECT CONVERT(datetime,'2017-03-01T18:23:02+07:00',127)
It seems that it works only specifying Z as time zone:
SELECT CONVERT(datetime,'2017-03-01T18:23:02Z',127)
This question already has answers here:
Conversion to datetime fails only on WHERE clause?
(6 answers)
Conversion failed when converting from a character string to uniqueidentifier error in SQL Server
(4 answers)
Closed 6 years ago.
I have been hitting a strange issue lately on SQL Server.
The application I am using is saving user's attributes in a table containing user/attribute/value records. I need to find whether a user is still valid using his end of validity date. The query I have been using is the following:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
The conversion is necessary because all values are stored as VARCHAR.
The query was working correctly but lately I have been hitting the following error:
SQL Error [241] [S0001]: Conversion failed when converting date and/or time from character string.
I though that the stored validity date was wrong. However, the value does match the correct format:
SELECT * FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
|userkey |AttrName |Value |
|--------|-----------|--------------------|
|574924 |VALIDTO |2016-07-31T23:59:59 |
I can even do a convert and show the result correctly:
SELECT CONVERT (DATE,Value, 120) AS Date FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
|Date |
|-----------|
|2016-07-31 |
However, as soon as I add the COUNT, the error is coming back.
Does any-one have an idea of what is going on in this case? Is it linked, in some way, to the value used?
EDIT
Thanks to the question at "Conversion to datetime fails only on WHERE clause?", I was able to rework my query as follow, which correct the issues I had:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE, CASE WHEN ISDATE(Value) THEN Value END, 120) < GETDATE();
The answer is that there is no guarantee of the order in which the WHERE clause operates. It looks like it may be applying the Convert of the value field before it filters the rows on userkey or attrName. Most likely the count is causing the plan to change which is just an unlucky side effect.
You chould retrieve the row with the userkey and attrname and then convert the value.
Curious, is there an index on the userkey field? And on attrname?
This question already has answers here:
SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
(19 answers)
Closed 6 years ago.
I am doing a clean up of a database but I am getting this error. I was to delete data less than 6 months old.
Query:
Delete from dbo.Jobs
where dtpDate <= '2016-04-27 15:23:00.000'
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.
The type is datetime
Try adding a cast to the query.
CAST( '2016-04-27 15:23:00.000' AS DATETIME)
DELETE FROM dbo.Jobs
WHERE dtpDate <= CAST('2016-04-27 15:23:00.000' AS DATETIME)
Your server probably has date format settings that are incompatible with yyyy-mm-dd. Check your current dateformat setting with dbcc useroptions. If it is incorrect, then change it with set dateformat.
The best solution is to make all queries independent of the current date format, e.g.
The ODBC locale-independent escape sequence
delete from dbo.Jobs where dtpDate <= {ts'2016-04-27 15:23:00.000'}
The ODBC convert() format
delete from dbo.Jobs where dtpDate <= convert(datetime, '2016-04-27 15:23:00.000', 120)
Use parameters when issuing SQL commands from an application.
I currently have dates stored in a general attribute field in the database as a string.
They are all stored in the format DD/MM/YYYY for example 01/01/2000
I am able to convert them them to datetime successfully by using the following in my select statement. For example CONVERT(DATETIME, attribute.field_value, 103) where attribute.field_value contains a date.
The SELECT statement works fine and returns the whole table with them correctly.
I can also return a column with todays date in the same format as follows CAST(getdate() AS datetime)
The problem occurs when I try to compare, now I only want to return everything that is newer than today in pseudo code that would dateNewerThanToday > dateToday
Therefore I have tried
WHERE CONVERT(DATETIME, attribute.field_value, 103) > CAST(getdate() AS datetime)
this gives me the error
Conversion failed when converting datetime from character string.
I have tried a multitude of cast/converts to get it to work. I have also wrapped by select so I am only doing it on dataset with the correct data.
Any help would be super useful! Many thanks in advance!!
A couple of things ..
You do not need to convert to GETDATE() to DATETIME data type as it already returns datetime data type.
Instead of CONVERT(DATETIME, attribute.field_value, 103)
use
CONVERT(DATETIME, attribute.field_value) or CAST(attribute.field_value AS DATETIME)
Add a where clause in your select to get only valid DATETIME values. something like
WHERE ISDATE(attribute.field_value) = 1
This will filter out any values which appears to be a date value but sql server doesnt see them as valid date values.
Important Not
Use appropriate data types. If this column is storing date values why not use the DATE or DATETIME data types.
I ran into this exact problem.
Values from a VARCHAR(50) column returned in the SELECT could be cast as date without issue. However when cast in a comparison in the WHERE clause the error occurred.
Of note, the error only occurred when I had other restrictions in the WHERE clause.
When I added ISDATE() to the WHERE clause, the error no longer occurred.
e.g. Shortened example of what worked:
SELECT CONVERT(DATE, mat.myAttributeColumn), mdct.myDateComparisonColumn
FROM myAttributeTable mat
JOIN myDateComparisonTable mdct ON mdct.key = mat.key
WHERE ISDATE(mat.myAttributeColumn) = 1
and mdct.myDateComparisonColumn < convert(DATE, mat.myAttributeColumn)
I am writing a query as following
SELECT DATEDIFF(year,Clmn_Dob,getdate()) AS DiffDate
FROM tblABCD
where Clmn_Dob is a NVARCHAR column. I want to find the age based on date of birth. But instead of this I am getting an error
Arithmetic overflow error converting expression to data type datetime
My string format is dd/MM/yyyy and getdate() format is MM/dd/yyyy.
I do not get any solution
You can use the CONVERT function:
SELECT
DATEDIFF(year,CONVERT(datetime, Clmn_Dob, 103),getdate()),
FROM tblABCD
and here doc:
http://msdn.microsoft.com/en-us/library/ms187928.aspx