sql server 条件where

发布于 2024-09-17 20:52:12 字数 186 浏览 2 评论 0原文

select * from table where category=@categoryid

我不确定这有多容易,但我无法理解它。我希望能够更改上述查询中的 where 子句,以便如果使用 0 而不是 1-2-3 或 4 作为 @categoryid ,它将选择所有类别。我的数据库中没有任何 0 的类别。

select * from table where category=@categoryid

I'm not sure how easy is this but I couldn't get my head around it. I want to be able to change where clause on above query so that if use 0 instead of 1-2-3 or 4 as @categoryid it would select all categories. i don't have any category with 0 in database.

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

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

发布评论

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

评论(5

若水般的淡然安静女子 2024-09-24 20:52:12

简单的。

select * from table where (category=@categoryid) OR (@categoryid = 0)

Simple.

select * from table where (category=@categoryid) OR (@categoryid = 0)
小ぇ时光︴ 2024-09-24 20:52:12

这可能应该分为 2 个单独的查询,除非您实际上希望在 @categoryid=0@categoryid<> 的情况下使用相同的完整聚集索引扫描执行计划;0

通过分为 2 个单独的查询,您可能会允许通过索引查找而不是完整扫描来满足 @categoryid 不为零的查询。

但是,如果表很小或者@categoryid 的选择性不是很强,那么这可能不是问题。

This should probably be divided into 2 separate queries unless you actually want the same execution plan of a full clustered index scan to be used both in the case that @categoryid=0 and @categoryid<>0

By dividing into 2 separate queries you will potentially allow the ones where @categoryid is not zero to be satisfied by an index seek rather than the full scan.

If the table is small or @categoryid is not very selective it might not be an issue however.

放飞的风筝 2024-09-24 20:52:12

当您想选择所有类别时,可以将其设置为 NULL,只需像这样修改选择

select * from table where category= ISNULL( @categoryid, category )

You can set it to NULL when you want to select all categories an just modify select like this

select * from table where category= ISNULL( @categoryid, category )
把昨日还给我 2024-09-24 20:52:12
select * from table where 
category BETWEEN @mincategoryid AND @maxcategoryid

Min 和 max 两者之一都是

  • 1(或 2 或 3 或 4),
  • 分别是 0 和一个大数

这也将使用索引。

select * from table where 
category BETWEEN @mincategoryid AND @maxcategoryid

Min and max will one of

  • both be 1 (or 2 or 3 or 4)
  • respectively 0 and a high number

This will use an index too..

自由范儿 2024-09-24 20:52:12

这是 SQL 而不是 PL/SQL。
您需要在发送请求之前测试该值,您不能要求 SQL 为您测试它。

This is SQL not PL/SQL.
You need to test the value before sending the request you can not ask to SQL test it for you.

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