首页 > 解决方案 > SQL Where Condition 无法找到不使用子选择或变量时找到的数据

问题描述

我有一个相当奇怪的现象。

DECLARE @SearchLE float
DECLARE @CompareLE float

SET @SearchLE = 
(
SELECT
    LastValue
FROM
    TableA
WHERE
    Articlenumber = 'example'
)

SELECT @SearchLE as SearchValue

返回 66,4 这是正确的。

SET @CompareLE =
(
SELECT TOP 1
            LastValue
        FROM
            TableB
        WHERE
            Articlenumber = 'example'
        AND
            LastValue= 
            --@SearchLE
            66.4
)

SELECT @CompareLE as CompareValue

返回 66,4 这显然也是正确的。

当我取消注释@SearchLE并注释掉 66.4 时,第二个SELECT语句返回 NULL。

有人可以向我解释吗?表中的两种数据类型都是浮点数。

这一切都在一个 SQL Server 数据库中,如果这很重要,我会使用 SQL Server Management Studio。请注意,我的返回值用逗号而不是句点分隔。

我也尝试TRY_CONVERT在这两个值上浮动,但没有成功。

标签: sqlsql-serversubquerywhere-clause

解决方案


Float is an approximate data type, so comparing a float with a float is usually not a good idea. Convert your values to decimal if you want to compare. If possible update the data type in the table, otherwise you have to convert it in your query, but that could cause performance issues if you have a large table.

e.g.

DECLARE @SearchLE decimal (8,2)

...

SET @CompareLE =
(
SELECT TOP 1
            LastValue
        FROM
            TableB
        WHERE
            Articlenumber = 'example'
        AND
            CAST( LastValue as decimal (8,2)) = @SearchLE

)

推荐阅读