Finding row causing error in type conversion in SQL Server - sql

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

Related

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

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

Convert varchar value to datetime in SQL Server 2012

In my import table I have the following column defined:
LFZ_begin VARCHAR(50) NULL
Now when I try to define the column in a view as DATETIME and call the view in SSMS, I get the following error message:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
In my view the column is defined as follows:
CONVERT(VARCHAR(50), CONVERT(DATETIME, LFZ_begin, 120)) AS LFZ_begin,
I need to expect the result value like that: 2020-09-04 00:00:0000
Does anyone have an idea for this issue?
You should fix your data model and never store date/time values as strings. In the meantime you can fix the view using try_ functions:
TRY_CONVERT(VARCHAR(50), TRY_CONVERT(DATETIME, LFZ_begin, 120)) AS LFZ_begin,
Note: This will eliminate the error on invalid formatted columns. Whether it ever returns a valid value depends on the data -- and you have shown no sample data so there is no way to suggest a solution to whatever the underlying problem is.

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)

SQL Server ISDATE() Error

I have a table and need to verify that a certain column contains only dates. I'm trying to count the number of records that are not follow a date format. If I check a field that I did not define as type "date" then the query works. However, when I check a field that I defined as a date it does not.
Query:
SELECT
count(case when ISDATE(Date_Field) = 0 then 1 end) as 'Date_Error'
FROM [table]
Column definition:
Date_Field(date, null)
Sample data: '2010-06-27'
Error Message:
Argument data type date is invalid for argument 1 of isdate function.
Any insight as to why this query is not working for fields I defined as dates?
Thanks!
If you defined the column with the Date type, it IS a Date. Period. This check is completely unnecessary.
What you may want to do is look for NULL values in the column:
SELECT SUM(case when Date_Field IS NULL THEN 1 ELSE 0 end) as 'Date_Error' FROM [table]
I also sense an additional misunderstanding about how Date fields, including DateTime and DateTime2, work in Sql Server. The values in these fields are not stored as a string in any format at all. They are stored in a binary/numeric format, and only shown as a string as a convenience in your query tool. And that's a good thing. If you want the date in a particular format, use the CONVERT() function in your query, or even better, let your client application handle the formatting.
ISDATE() only evaluates against a STRING-like parameter (varchar, nvarachar, char,...)
To be sure, ISDATE()'s parameter should come wrapped in a cast() function.
i.e.
Select isdate(cast(parameter as nvarchar))
should return either 1 or 0, even if it's a MULL value.
Hope this helps.
IsDate takes a character string or exression that yeilds a character string as it's argument
The problem is this method ISDATE() only admits arguments of type datetime and smalldatetime within the "time" types, so it won´t work if you are using date type.
Also if you use date as type for that field, you won´t have to check the information there because it won´t admit other type of field.
You shoul only check for null values in your column, that´s all.

Converting SQL Server null date/time fields

Whenever the value is null for this query
SELECT ISNULL(someDateTime,'')
FROM someTable
the result is
someDateTime
------------
1900-01-01 00:00:00.000
I want it to be "No", so if I run this:
SELECT ISNULL(someDateTime,'No')
FROM someTable
then there's this error:
Conversion failed when converting datetime from character string.
How to do it? Thanks in advance!
The result of the expression will need to be a single type. If you want a character string (and you do, since 'No' is not a DateTime), you'll need to convert the datetime to such a string:
SELECT ISNULL(cast(someDatetime as varchar(20)), 'No') FROM someTable
As others have suggested, though, code like this smells bad, and you may want to pass the null to a client component and do the conversion there.
isnull() is trying to convert the second argument to the datatype of the field you specify in the first argument.
If you are going to be returning a string you need to cast the DateTime field to a string type so that isnull() can work properly - see Michael Petrotta's answer for a way to accomplish this.
You're still selecting a DateTime column, and so the result of that expression still needs to be a DateTime value rather than a string. To suggest an appropriate work-around, we'll need to know more about what you're really trying to do with this data.
You can't as such directly. It's easier to trap NULL in the client and change it to "no" there.
However, you could use a token value such as "17530101" which is a valid datetime, or CONVERT SomeDateTime first to varchar.
Otherwise, we need more info on why etc
In your Update Stored Proc: Update your previous date value to a new Null value:
.Parameters.AddWithValue("#Date_Value", Nothing).IsNullable = True