sql - 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
在这两个值上浮动,但没有成功。
解决方案
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
)
推荐阅读
- django - Django 将外键更改为 BigInt
- javascript - 将元素放置在屏幕中央,即使移动设备已缩放(CSS 或 JS)
- css - 在 WKWebView 中看到图像下方的空白?
- pycharm - mypy 可以检测到错误的 TypedDict 返回类型吗?
- java - 抛出异常 Java 8 Lambda
- javascript - 按下按钮后停止和启动动画(Javascript)
- python - 在 cython 中使用 np.where 作为索引
- python - 四舍五入并缩短时间
- android - Android:无法更新 Firestore 中的文档字段
- c# - 错误:当从数据库中过滤的 DataGridView 表中的图像数据转换为 pdf 时