子查询返回所有值,然后应用 where 条件

Sub query returning all values and then applying where condition

即使数据几乎相似,我也只在一个特定的 environment/database 中遇到查询问题。这是简化的场景:

Table A - 一列 - Id(长)

Id
1
2
3

Table B - 两列 - value(varchar) 和 field2(varchar)

  Value Field2
1)abc   NotKey
2)Test  NotKey
3)1     Key
4)1.56  NotKey

当我运行查询

select * from table a
where id in(select value from table b where Field2 = 'Key')

我收到错误

结果:将 varchar 值 'abc'(之前我将此值错误地设为 'NotKey')转换为数据类型 int 时转换失败。

在一个数据库上。在其他三个数据库中,值 returns 正确为“1”。

我正在使用 SQL Server 2008。这可能是什么问题?

您在此实例中必须有一条记录不遵循与以前相同的模式。尝试 运行 以下查询来查找您的错误数据。您可以修复记录或向您正在使用的查询添加数字检查。

select *
from table
where Field2 = 'Key'
    and (ISNUMERIC(Value) = 0
        OR CHARINDEX('.', Value) > 0);

筛选查询:

select *
from table a
where id in
(
    select value
    from table b
    where Field2 = 'Key'
        and ISNUMERIC(value) = 1
        and CHARINDEX('.', Value) = 0
);

您为导致错误的过滤器提供了错误的过滤器。

错误只发生在你select:

select * from tablea
where id in(select value from tableb where Field2 = 'NotKey')

您必须投射其中一列

select * from tablea
where cast( id as nvarchar(20)) in(select value from tableb where Field2 = 'NotKey')

http://sqlfiddle.com/#!6/e9223/23