SQL Error : Conversion failed when converting date and/or time from character string - sql

I'm trying to convert a varchar column to date or datetime but I don't understand why it's not possible it should work and I don't see any kind of error.
The column values is 31-07-2017 and the type is Varchar(250). I tried convert and cast and I get the same error:
Conversion failed when converting date and/or time from character string.
Does anyone have any idea on why it's like this?

The conversion error is because your session setting is other than DATEFORMAT dmy or varchar values do not conform to DMY format.
For the latter case, run the query below to identify problem values:
SELECT YourDateColumn AS InvalidDate
FROM dbo.YourTable
WHERE
YourDateColumn IS NOT NULL
AND TRY_CONVERT(date, YourDateColumn, 103) IS NULL;
As #TimBiegeleisen mentioned in a comment, it is best to choose the most appropriate column type (date in this case) for the data to be stored. Not only will this avoid errors like this, it will improve performance and better ensure data integrity.

I found the issue, it's a very very stupid mistake, there was one column with a text format I couldn't see it because I checked with length, but the SQL gives max length so I used group by and manually check dates until I found one column that's not correct in 1 m account records

Related

I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format

I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format.
Please suggest how to approach this?
I did tried but it is failing as it is failing due to invalid month.
Is there a way i can first identify what format the date is and then based on case statement i might convert.
or something easy way? Please
I trust you've learnt your lesson and you're now going to store these dates in the date data type.
Your two different date formats actually aren't important, Oracle already is a little over accepting when it comes to separating characters.
e.g
to_date('01/01/1900','dd-mm-yyyy')
Does not error
I did tried but it is failing as it is failing due to invalid month.
Your error is coming because you've allowed a value that doesn't match either of those formats into your string column.
If you are on version 12.2 at least (which you should be in 2020) then you can use the validate_conversion function to identify rows that don't convert to a date with your format (https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/VALIDATE_CONVERSION.html#GUID-DC485EEB-CB6D-42EF-97AA-4487884CB2CD)
select string_column
from my_table
where validate_conversion(string_column AS DATE,'dd/mm/yyyy') = 0
The other additional helper we got in 12.2 was the on conversion error clause of to_date. So you can do.
alter table my_table add my_date date;
update my_table set my_date = to_date(my_string default null on conversion error,'dd/mm/yyyy');
If you are confident that there is no other format than those two, a simple approach is replace():
update mytable set mystring = replace(mystring, '/', '-');
This turns all dates to format dd-mm-yyyy.
I would suggest taking a step forward and convert these strings to a date column.
alter table mytable add mydate date;
update mytable set mydate = to_date(replace(mystring, '/', '-'), 'dd-mm-yyyy');
This will fail if invalid date strings are met. I tend to consider that a good thing, since it clearly signals that this a problem with the data. If you want to avoid that, you can use on conversion error, available starting Oracle 12:
to_date(
replace(mystring, '/', '-') default null on conversion error,
'dd-mm-yyyy'
)
Then you can remove the string column, which is no longer needed.

Showing this error "Conversion failed when converting date and/or time from character string." in SQL

My sp is
EXEC _REPORTS #StartDate=N'17-Sep-2016',
#EndDate=N'17-Sep-2016',
#CustomerID=0,
#ProductID=0,
#BranchID=0,
#NumberOfRecords=100,
#PageNo=1,
#IsBuy=1
here the region of date used in where
AND FCSB.FCBuySellDate
BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)
The reason is primarily you are getting some wrong formatted data to convert, For example
declare #StartDate nvarchar(15) = N'17-Septt-2016'
select CONVERT(datetime,#StartDate,105)
You will get this error
Conversion failed when converting date and/or time from character string.
If you get correct date you get it converted, one way to ignore this error is to do TRY_CONVERT which willl return NULL. Best way to solve this problem is to identify why it is getting wrong date as parameter and fix that.
select TRY_CONVERT(datetime,#StartDate,105)
check for null value in FCSB.FCBuySellDate. It might be cause of an error
try this
AND FCSB.FCBuySellDate BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)
AND isnull(FCSB.FCBuySellDate,'') <> ''
Also try this, convert column in datetime
AND CONVERT(datetime,FCSB.FCBuySellDate) BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)

Casting varchar as date

I think I've read just about every thread on this topic and none of them are solving my problem.
First of all, the database I'm working with has all date fields set to a varchar data type, which drives me insane because I constantly have to cast or convert whenever I'm working with any queries involving dates.
The query I'm working with at the moment is supposed to pull a list of medical patients who all have a certain diagnosis, but that diagnosis has to have been given before a certain date. Here's what I've got.
SELECT DISTINCT
pd.PatientID,
pd.PatientName,
pmh.DateOfOnset
pmh.DiagnosisCode
FROM PatientDemographic pd JOIN PatientMedicalHistory pmh ON pd.PatientID = pmh.PatientID
WHERE pmh.DiagnosisCode = '401.1'
AND CAST(pmh.DateOfOnset as Date) > CAST('12/31/2014' as Date)
I'm getting an error that says "Conversion failed when converting date and/or time from character string." It's telling me the error is on Line 1 though (the SELECT DISTINCT line) so that's not really helpful and I'm not sure what I need to fix.
As I mentioned, the DateOfOnset field has a varchar data type, and I need to find any of those dates that came before the end of December, 2014. I've tried to remedy this error by trying different combinations of the CAST statements -- I even tried including a cast on the date field in the SELECT statement, and I'm still getting the same error.
I was working on another query earlier that required me to find all patient appointments from within a certain time frame, and for that query, I had my WHERE clause set up like:
WHERE Cast(VisitDate as Date) BETWEEN CAST('01/01/2014' as Date) AND CAST('12/01/2014' as Date)
...and it worked perfectly fine. Since I've got my current query set up virtually the same way, I'm not sure why I'm getting that conversion error.
You have wrong dateformat:
SET DATEFORMAT dmy;
SELECT CAST('12/31/2014' as Date);
--Conversion failed when converting date and/or time from character string.
You could set it to mdy before executing your query.
SET DATEFORMAT mdy;
SELECT CAST('12/31/2014' as Date);
LiveDemo
or use CONVERT with style 101:
SET DATEFORMAT dmy;
SELECT CONVERT(DATE,'12/31/2014',101)
If you really need to store DATE as VARCHAR use at least culture independent type like ISO-8601.
SET DATEFORMAT dmy;
SELECT CAST('20140201' as Date);
-- 01.02.2014
SET DATEFORMAT mdy;
SELECT CAST('20140201' as Date)
-- 01.02.2014
It sounds like SQL is not able to convert the stored strings into dates. This would explain why CAST(pmh.DateOfOnset as Date) fails where Cast(VisitDate as Date) does not--the latter might not have any mis-formatted dates.
Best-case solution is to convert your table columns to the proper datatypes. Second-best case, add columns containing the proper datatypes, and convert the data over; you'd have to fix any existing bad data, as well as convert data on the fly as it's loaded (yuck). Another option, add a calculated column, though you'll have problems with the afore-mentioned invalid dates. (What version of SQL do you have? Later versions have the isdate function, which might help here.)
If modifying tables is not an option, you're probably stuck writing queries that have to assume some of the data is invalid (bad format).

Finding row causing error in type conversion in SQL Server

I am trying to cast a column as smalldatetime from varchar. There are some rows containing errors, how can I find them?
SELECT
PA.EAR_TAG
,ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE) as HB_Date
,Y.[DATE OF MOVEMENT] as Y_Date
,DATEDIFF(DAY, ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE), cast(Y.[DATE OF MOVEMENT] as smalldatetime))
FROM
DairyTelomere.dbo.PROJECT_ANIMALS AS PA
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_BULL AS B ON Pa.EAR_TAG = B.EAR_TAG
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_HEIFER AS H ON PA.EAR_TAG = H.EAR_TAG
LEFT JOIN
DairyTelomere.dbo.Young_Stock_culls AS Y ON PA.EAR_TAG = Y.Ear_Tag
The error I get is:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
I know that if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions).
Any ideas will be greatly appreciated.
you can use the isdate to get a list of all the ones that are not converting for you. You dont need to change the column type to use this so i am confused by your statement
if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions)
Will help more if you can clarify but this query should get you a list of rows that have bad date values.
select table.date_as_varchar
from table
where isdate(table.date_as_varchar) = 0
adding to #workabyte answer you can also try using TRY_PARSE, TRY_CAST OR TRY_CONVERT, all of them return NULL if the conversion failed, that way you can know wich rows caused the error.
TRY_PARSE
as the documentation says:
Use TRY_PARSE only for converting from string to date/time and number
types. For general type conversions, continue to use CAST or CONVERT.
Keep in mind that there is a certain performance overhead in parsing
the string value.
Usage example:
SELECT TRY_PARSE(your_date AS DATETIME USING 'es-ES') as date
FROM your_table
es-ES is a culture parameter,different culture paramaters yield different results in your conversions, you can find the full list of parameters in the documentation
TRY_CONVERT
as the documentation says:
TRY_CONVERT takes the value passed to it and tries to convert it to
the specified data_type. If the cast succeeds, TRY_CONVERT returns the
value as the specified data_type; if an error occurs, null is
returned. However if you request a conversion that is explicitly not
permitted, then TRY_CONVERT fails with an error.
Usage example:
SELECT TRY_CONVERT(DATETIME,your_date,103) as date
FROM your_table
The 103 being the style/format of the date you are converting, here you can find a list of the formats avaliable
TRY_CAST
as the documentation says:
TRY_CAST takes the value passed to it and tries to convert it to the
specified data_type. If the cast succeeds, TRY_CAST returns the value
as the specified data_type; if an error occurs, null is returned.
However if you request a conversion that is explicitly not permitted,
then TRY_CAST fails with an error.
Usage example:
SELECT TRY_CAST(your_date AS DATETIME) as date
FROM your_table

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value
Such as, Column A with value ‘07/09/2012 14:13:34’
Now, I want to update column A to yyyymmdd by statement
Update Change_Date
SET A = CONVERT(VARCHAR(8),A,112)
It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.
Any help will be greated, thank you!
A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.
I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.
What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.
You can select the date column in specified format or make a view which selects the column value in yyyymmdd format:
SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date
It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR. I believe 112 is yyyymmdd format.
I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE. If for instance you want to retrieve the dates with specific format, that's the time you convert your date.
Hope this makes sense.