【问题标题】:How can I take an optional SQL where clause in a simple Select statement如何在简单的 Select 语句中采用可选的 SQL where 子句
【发布时间】:2018-09-06 10:58:03
【问题描述】:

我有一个存储过程,我需要在一个表中搜索所有结果(大部分时间),但有时我知道我在寻找哪个结果集。

所以我在 where 子句中需要一个可选参数。如果参数包含在命令行中,它会被设置,否则默认为 0,我将整个范围设置为返回。

这可行,但必须有更优雅的解决方案。

CREATE PROCEDURE [dbo].[GetItemDetails] 
    @itemId int = 0 
AS
BEGIN
    select * from myEntities
    where @itemId > (case when @itemId = 0 then @minId else @itemId - 1 end)
    and @itemId < (case when @itemId = 0 then @maxId else @itemId + 1 end)
END

【问题讨论】:

  • 更正:应该是 select * from ... where itemId > @itemId... 这是字段与变量的错字。不知道如何编辑原始帖子。

标签: sql select conditional where-clause


【解决方案1】:

所以像这样?不知道它有多“优雅”。

select * from myEntities
where ((@ItemId = 0)OR(@ItemId <> 0 AND ItemId = @ItemId))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2015-07-26
    • 2013-07-07
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2013-06-14
    相关资源
    最近更新 更多