There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.