I’ve got one table with alphanumeric codes. In this particular instance, I am not concerned with the codes that are alphanumeric in nature, only those that contains integers. I wrote a small query to find a the subset of codes that I needed:
select CAST(icd as float) as icd
from
(
select i.icd
from icd as i
where icd like '952%' or icd like '806%' or icd like '3440%' or icd like '3441'
)t
This returns me a list of the codes I needed. However, when I try to use a where clause like:
where icd between 80600 and 80610 the query fails, telling me that it can’t convert the varchar datatype to int. However, if I do something like
select CAST(icd as float) as icd,icd+10
from
(
select i.icd
from icd as i
where icd like '952%' or icd like '806%' or icd like '3440%' or icd like '3441'
)t
I can add ten to each code and it runs, meaning that they are in fact integers. I want to use the where clause like this because codes 80600-80610 should be labeled X and 80611-80620 they should be labeled Y. I can do this manually for each code, but I’d like to be more extensible than that.
How can I make sure that SQL Server only looks at the derived table when using this where clause, instead of failing?
Filters run before results are cast
What you’re doing is casting results not column values when query runs (and does all the filtering). Filters (
whereclause) are evaluated before result values are being cast.In order to still work with the same result set as you show in your example the easiest way is to use a CTE instead of a sub-query and then do additional filtering on that:
Whether CTEs are more/less readable than sub-queries is a matter of endless discussion/arguments. But in this case where we reuse the same table expression to get X and Y labelled results it uses less code compared to what would be needed when doing the same with sub-queries. In this case it is by far more readable.
Data to be cast must be numeric of course
When you’re casting data you have to make sure it actually can be cast to result type. If your value is
064 Vthis is clearly not a number hence can’t be cast. a call toisnumericcan help here: