Filters run before results are cast.
What you do is distinguish the results from the columns when the query is executed (and does all the filtering). Filters ( where ) are calculated before the result values โโare returned.
To work with the same result set as in your example, the easiest way is to use CTE instead of a subquery, and then additional filtering:
with codes as ( select cast(icd as int) as icd from icd where icd like '952%' or icd like '806%' or icd like '3440%' or icd like '3441' ) select icd, 'X' as label from codes where icd between 80600 and 80610 union all select icd, 'Y' from codes where icd between 80611 and 80620
Whether CTEs are more / less readable than subqueries is a matter of endless discussion / argument. But in this case, when we reuse the same table expression to get the marked results of X and Y , it uses less code than what would be necessary if we did the same with the subqueries. In this case, it is much more readable.
The data to be produced must, of course, be numerical.
When you produce data, you must make sure that they can be distinguished from the type of result. If your value is 064 V , this is clearly not a number, so it cannot be distinguished. calling isnumeric can help here:
with codes as ( select cast(icd as int) as icd from icd where isnumeric(icd) = 1 and ( icd like '952%' or icd like '806%' or icd like '3440%' or icd like '3441' ) ) select icd, 'X' as label from codes where icd between 80600 and 80610 union all select icd, 'Y' from codes where icd between 80611 and 80620
source share