I have a query with the below WHERE clauses
WHERE
I.new_outstandingamount = 70
AND ISNUMERIC(SUBSTRING(RA.new_stampernumber,7, 4)) = 1
AND (DATEDIFF(M,T.new_commencementdate, SUBSTRING(RA.new_stampernumber,7, 10)) >= 1)
AND RA.new_applicationstatusname = 'Complete'
AND I.new_feereceived > 0
AND RA.new_stampernumber IS NOT NULL
AND T.new_commencementdate IS NOT NULL
RA.new_stampernumber is a string value which contains three concatenated pieces of information of uniform length. The middle piece of info in this string is a date in the format yyyy-MM-dd.
In order to filter out any rows where the date in this string in not formatted as expected I do a check to see if the first 4 characters are numeric using the ISNUMERIC function.
When I run the query I get an error message saying
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The line that is causing this error to occur is
AND (DATEDIFF(M,T.new_commencementdate, SUBSTRING(RA.new_stampernumber,7, 10)) >= 1)
When I comment out this line I don’t get an error.
What is strange is that if I replace
AND ISNUMERIC(SUBSTRING(RA.new_stampernumber,7, 4)) = 1
with
AND SUBSTRING(RA.new_stampernumber,7, 4) IN ('2003','2004','2005','2006','2007','2008','2009','2010', '2011', '2012','2013','2014','2015'))
the query runs successfully.
Whats even more strange is that if I replace the above working line with this
AND SUBSTRING(RA.new_stampernumber,11, 1) = '-'
I get the error message again. But if I replace the equals sign with a LIKE comparison it works:
AND SUBSTRING(RA.new_stampernumber,11, 1) LIKE '-'
When I remove the DATEDIFF function and compare the results of each of these queries they all return the same resultset so it is not being caused by different data being returned by the different clauses.
Can anyone explain to me what could be causing the out-of-range error to be thrown for some clauses and not for others if the data being returned is in fact the same for each clause?
Thanks,
Neil
Different execution plans.
There is no guarantee that the
WHEREclauses are processed in particular order. Presumably when it works it happens to filter out erroring rows before attempting the cast to date.Also
ISNUMERICitself isn’t very reliable for what you want. I’d change theDATEDIFFexpression to something like the below