Date Cast/Convert - sql

I get errors like "Conversion failed when converting date and/or time from character string." All I have to do is add a WHERE clause where I compare values having (datetime, null) format (like 2014-07-29 00:00:00.000) and values having (decimal (8,0), null) format (like 20140723).
I tried to cast both these values as varchar, tried to cast one of them as date - nothing works.
At the same time, when I ran a previous query without the WHERE clause, the following join condition worked perfctly:
on cast(DATE_1 as date)= cast(cast(DATE_2 as varchar) as date)
Any ideas? Thanks a bunch!

Related

How to convert YYMMDDhhmm formatted NVARCHAR into YYYY-MM-DD hh:mm:ss formatted DATETIME?

For example:
The value 2208111603(nvarchar) needs to be converted to 2022-08-11 00:00:00(datetime).
The things I have tried and the corresponding errors I've got so far as follow:
CAST(DATE_TIME AS numeric) works but CAST(CAST(DATE_TIME AS numeric) AS datetime) returns Arithmetic Overflow Error.
convert(datetime2, CAST(DATE_TIME AS numeric), 105) returns
Explicit conversion from data type numeric to datetime2 is not allowed
CONVERT(datetime2, DATE_TIME , 105) returns
Conversion failed when converting date and/or time from character
string.
CONVERT(datetime2, CONVERT(CHAR(10), DATE_TIME), 105) returns
Conversion failed when converting date and/or time from character
string.
Finally, I tried PARSE(DATE_TIME AS date USING 'en-US') which resulted in
Error converting string value '2208111603' into data type date using
culture 'en-US'.
The SQL Server's CONVERT function also has some built-in formats as a third parameter for converting varchar to datetime. So, I tried SELECT convert(datetime,'2208111603',112) which resulted in the same error (Msg 241):
Conversion failed when converting date and/or time from character
string.
Any help would be much appreciated!
With just a bit of string manipulation...
Note: this will assume century of 20
Example
Declare #S varchar(50) ='2208111603'
Select try_convert(datetime,stuff(stuff(#S,7,0,' '),10,0,':'))
Results
2022-08-11 16:03:00.000
A little bit ugly, but to overcome the century indicator you an nest a little logic to conditionally add 19.
Declare #S varchar(50) ='6408111603'
Select try_convert(datetime,case when left(#S,2)>'50' then '19' else '' end + stuff(stuff(#S,7,0,' '),10,0,':'))

Parse values of different type to date

I'm trying to parse certain columns into a date format and have had success doing so, but have run into an error due to inconsistency that lies in the data.
My date columns are currently integers in the form of YYYYMMDD, so I've used the following in the select statement to parse into dates:
CONVERT(datetime, CAST(date_column AS CHAR(8)), 112)
This works as expected, transforming my data into a YYYY-MM-DD format.
I run into the following error though:
Conversion failed when converting date and/or time from character
string.
After looking through the data a bit, it turns out I have some cases of inconsistent data values, such as -1 and 10630 instead of the expected YYYYMMDD value.
Do I just need to add a WHERE statement to only apply CONVERT and CAST to YYYYMMDD fields while filtering out fields with bad data? If so, how would I do this, or is there a better way?
Thanks in advance
Let me assume you are using SQL Server, based on the syntax of your SQL. You shouldn't actually need the 112. 'YYYYMMDD' is the default date format for SQL Server.
In any case, you can use TRY_CONVERT():
TRY_CONVERT(datetime, CAST(date_column AS CHAR(8)), 112)
This returns NULL if the value cannot be converted. You can find the offending values using:
select date_column
from t
where try_convert(datetime, cast(date_column as char(8)) is null and
date_column is not null;
Use Parse() or Try_parse()
select parse('22-JAN-1989' as date)
select parse('04-March-1992' as date)
select parse('03/10/2020' as date)
select parse('07-05-1958' as date)
select parse('Aug 25,2016' as date)
Every example above returns a valid date.
You can also add USING 'en-US' or such if you want a different culture.
If you are getting numeric values, and you know the starting date, use
select IsNull(try_parse('16500' as date),dateadd(d,cast('16500' as int),'1/1/1980'))

Converting date and/or time from character string

Can someone please tell me what 's wrong with this code that I get error:
Conversion failed when converting date and/or time from character string.
, iif(t1.medbuildcmpltdt IS NOT NULL,cast(datediff(day, t1.medbuildcmpltdt,t1.orderingtoolbuildcmpltdt)AS nvarchar(255)), cast(t1.orderingtoolbuildcmpltdt AS nvarchar(255)) AS 'Main_Days Build'
Conversion failed when converting date and/or time from character string.
The problem is where SQL Server wants a date or datetime and is receiving a string. The only thing in the code you provided that requires a date or datetime is
datediff(
day,
t1.medbuildcmpltdt,
t1.orderingtoolbuildcmpltdt
)
So, t1.medbuildcmpltdt or t1.orderingtoolbuildcmpltdt is a string ([n][var]char) and contains values that cannot be interpreted as valid date or datetime values.

Convert from varchar into date in SQL Server

This looks easy solution but I can't seem to figure out as to why this is not working for me. I have a column that has data like this:
DateField
----------
12/16/2016
11/06/2016
All I want to do is to convert from varchar into a date column, but I am getting this error:
Conversion failed when converting date and/or time from character string.
Here is my simple query:
select convert (date, DateField) as convertedField
from myTable
Nothing wrong with the two examples you have given. There are some bad dates in your table which cannot be converted to date.
Use TRY_CONVERT function for bad dates it will return NULL
select TRY_Convert(date,DateField)
From myTable
You should always store dates in DATE/DATETIME datatype.
If you want to see the records which cannot be converted to date then
select DateField
From myTable
Where TRY_Convert(date,DateField) IS NULL
If working with a specific date format like mm/dd/yyyy You can specify it in Convert() function like the following
CONVERT(DATETIME,DATAFIELD,101)
If it still is not working, use TRY_CONVERT() to get which rows are throwing this exception:
SELECT *
FROM TBL
WHERE TRY_CONVERT(DATETIME, DATAFIELD, 101) IS NULL
This will return rows that cannot be converted
TRY_CONVERT() will return NULL if conversion failed
Read more about DateTime formats here:
SQL Server CONVERT() Function tutorial
Read TRY_CONVERT MSDN Article
You need to specify the format of date time while formatting. The date in your table is currently in U.S format so you should pass the third argument 101 in your convert function.
SELECT CONVERT(date,[DateField],101) FROM myTable;
Working Fiddle here http://rextester.com/NYKR49788
More info about date time style here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

SQL - Convert String to Date and compare - Conversion failed when converting datetime from character string

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)