对浮点字段的SQL服务器'like'会产生不一致的结果

ros*_*533 2 sql t-sql sql-server

LIKE用来返回浮点字段的匹配数字结果.似乎一旦小数点左边有超过4位数字,就不会返回与小数点右侧的搜索项匹配的值.这是一个说明情况的例子:

CREATE TABLE number_like_test (
  num [FLOAT] NULL
)

INSERT INTO number_like_test (num) VALUES (1234.56)
INSERT INTO number_like_test (num) VALUES (3457.68)
INSERT INTO number_like_test (num) VALUES (13457.68)
INSERT INTO number_like_test (num) VALUES (1234.76)
INSERT INTO number_like_test (num) VALUES (23456.78)

SELECT num FROM number_like_test
WHERE num LIKE '%68%'
Run Code Online (Sandbox Code Playgroud)

该查询不返回值为12357.68的记录,但它确实返回值为3457.68的记录.同样使用78而不是68运行查询不会返回23456.78记录,但使用76将返回1234.76记录.

所以要回答这个问题:为什么有一个更大的数字会导致这些结果发生变化?如何更改查询以获得预期结果?

And*_*mar 5

like运营商需要一个字符串作为左边的值.根据文档,从转换floatvarchar可以使用几种样式:

Value         Output
0 (default)   A maximum of 6 digits. Use in scientific notation, when appropriate.
1             Always 8 digits. Always use in scientific notation.
2             Always 16 digits. Always use in scientific notation.
Run Code Online (Sandbox Code Playgroud)

默认样式适用于六位数3457.68,但不适用于七位数13457.68.要使用16位而不是6位,您可以使用convert并指定样式2.样式2表示数字3.457680000000000e+003.但这不适用于前两位数字,并且您可以+003免费获得意外的指数.

最好的方法可能是转换floatdecimal.该转换允许您指定比例和精度.使用scale 20和precision 10,float表示为3457.6800000000:

where   convert(decimal(20,10), num) like '%68%'
Run Code Online (Sandbox Code Playgroud)