【发布时间】:2011-01-17 11:01:13
【问题描述】:
我有一列 TypeCode varchar(20),它的值有“1”、“2”、“3”、“FOO”、“BAR”。我需要找到小于参数值的最大整数。像这样的:
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
这在大多数情况下都有效,但在某些查询中,SQL Server 决定将其转换为类似的内容(根据查询计划)。
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')
该查询显然会产生以下错误:
Conversion failed when converting the varchar value 'FOO' to data type int.
我尝试创建一个不包含“FOO”和“BAR”值的 table2 视图并改为加入该视图,但查询计划仍然相同。
您知道防止优化器更改查询的方法吗?
PS:我知道表的设计不是最好的,但这是一个遗留数据库,我无法更改它。
【问题讨论】: