可选的where子句取决于参数值

时间:2015-07-21 12:18:42

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

我希望此查询的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

有办法吗?

2 个答案:

答案 0 :(得分:0)

SELECT
 //...
FROM
(

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

答案 1 :(得分:0)

你应该试试这个,

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