I have a column TypeCode varchar(20) that has values like '1', '2', '3', 'FOO', 'BAR'. I need to find the maximum integer which is less than the value of parameter. Something like this:
select max(TypeCode) TypeCode
from table1 a
left join table2 b on b.table1id = a.id
and b.TypeCode not in ('FOO', 'BAR')
where b.TypeCode < @MaxType
Which works most of the time, but in some queries SQL Server decides to convert it to something like this (according to the query plan).
select max(TypeCode) TypeCode
from table1 a
left join table2 b on b.table1id = a.id
and b.TypeCode < @MaxType
and b.TypeCode not in ('FOO', 'BAR')
That query obviously produces the following error:
Conversion failed when converting the varchar value 'FOO' to data type int.
I tried creating a view of table2 without the 'FOO' and 'BAR' values and joining the view instead but the query plan is still the same.
Do you know of a way to prevent the optimizer from changing the query?
PS: I know the design of the table is not the best but this is a legacy database and I can't change it.