【问题标题】:Optional where clause depending on parameter value取决于参数值的可选 where 子句
【发布时间】:2015-10-10 21:28:12
【问题描述】:

我希望此查询的 where 语句是可选的,具体取决于参数 @RetrieveAll 的值。如果@RetrieveAll 为false/null,则使用where 语句,如果为true,则应忽略它。

    @IncludeErrors bit = 1,
    @IncludeAccess bit = 1,
    @IncludeLogins bit = 1,
    @RetrieveAll bit = NULL
SELECT
 //...
FROM
(

) AS a
WHERE
a.RowNumber BETWEEN @ItemCountStart AND @ItemCountEnd

有没有办法做到这一点?

【问题讨论】:

标签: sql stored-procedures sql-server-2008-r2


【解决方案1】:
SELECT
 //...
FROM
(

) AS a
WHERE
(a.RowNumber BETWEEN @ItemCountStart AND @ItemCountEnd AND @RetrieveAll IS NULL)
OR
@RetrieveAll IS NOT NULL

【讨论】:

    【解决方案2】:

    你应该试试这个,

    Select * from Tablename a
    Where 
    1 = case when isnull(@RetriveAll,0) == 0 then 
            case when a.RowNumber BETWEEN @ItemCountStart AND @ItemCountEnd then 1 else 0 end
        else 1 end
    

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 2010-10-23
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多