如何根据 varchar 列上基于数字的 RANGE 过滤器选择行?

发布于 2024-12-18 22:52:30 字数 367 浏览 2 评论 0原文

如果我有一个长度为 30 的 varchar 列:

[SpecificCode] --> varchar(30) 在名为 [Item] 的数据库表中

如果我必须查询此表行以获取

SpecificCode 在 789 到 15000 之间

的所有行可能是什么在 TSQL 中进行 SELECT 的最快方法是什么? (长度为30的varchar字段需要进行范围测试)

SELECT *
FROM Item
WHERE Item.SepecificCode --how to filter between 789 and 15000?

If I have a varchar column which has the length 30:

[SpecificCode] --> varchar(30) in a db table called [Item]

And if I have to query this table rows to obtain all the rows which have

SpecificCode between 789 and 15000

What may be the fastest way to SELECT in TSQL? (Range test is needed on a varchar field with length 30)

SELECT *
FROM Item
WHERE Item.SepecificCode --how to filter between 789 and 15000?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

土豪 2024-12-25 22:52:30

假设该列充满非数字垃圾但没有小数

SELECT *
FROM Item
WHERE
    RIGHT('00' + Item.SpecificCode, 5) BETWEEN '789' and '15000'
    AND
    ISNUMERIC(Item.SpecificCode) = 1;

如果只是整数

SELECT *
FROM Item
WHERE
    CAST(Item.SpecificCode AS int) BETWEEN 789 and 15000;

如果也浮动:

SELECT *
FROM Item
WHERE
    CAST(Item.SpecificCode AS float) BETWEEN 789 and 15000
    AND
    FLOOR(CAST(Item.SpecificCode AS float)) = CAST(Item.SpecificCode AS int)

Assuming the column is full of non-numeric rubbish but no decimals

SELECT *
FROM Item
WHERE
    RIGHT('00' + Item.SpecificCode, 5) BETWEEN '789' and '15000'
    AND
    ISNUMERIC(Item.SpecificCode) = 1;

If just integers

SELECT *
FROM Item
WHERE
    CAST(Item.SpecificCode AS int) BETWEEN 789 and 15000;

If floats too:

SELECT *
FROM Item
WHERE
    CAST(Item.SpecificCode AS float) BETWEEN 789 and 15000
    AND
    FLOOR(CAST(Item.SpecificCode AS float)) = CAST(Item.SpecificCode AS int)
夕嗳→ 2024-12-25 22:52:30

它会是这样的:

SELECT *
FROM Item
WHERE cast(Item.SepecificCode as integer) >= 789 and cast(Item.SepecificCode as interger) <= 15000

但为了提高性能,您应该在 SepecificCode 列中创建一个索引

It would be something like this:

SELECT *
FROM Item
WHERE cast(Item.SepecificCode as integer) >= 789 and cast(Item.SepecificCode as interger) <= 15000

but to improve performance you should create a index in the SepecificCode column.

沧桑㈠ 2024-12-25 22:52:30

尝试强制 sql 将列作为 INT 读取

SELECT * FROM Item WHERE Item.SepecificCode+0 between 789 and 15000;

,据我所知,该列上的任何索引都是无用的,因为它们是为 varchar 数据而不是整数创建的,请尝试使用以下命令查看:

EXPLAIN SELECT * FROM Item WHERE Item.SepecificCode+0 between 789 and 15000;

Try forcing sql to read the column as a INT

SELECT * FROM Item WHERE Item.SepecificCode+0 between 789 and 15000;

AFAIK any index you have on that column is usless, beacause they are created for varchar data not integers, try see that with:

EXPLAIN SELECT * FROM Item WHERE Item.SepecificCode+0 between 789 and 15000;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文