2015-07-11 66 views
1

我有以下查詢,其中如果@Searchby的輸入是1,我想省略過濾器created_by = @searchBy。我怎樣才能做到這一點?根據輸入刪除where子句的一部分

CREATE PROC [dbo].[RptCashCollectionInner] 
    @branchId int, 
    @searchBy int, 
    @paidDate datetime 
AS 
BEGIN 
    SELECT Id 
    FROM reading 
    WHERE created_by = @searchBy 
     AND branch_id = @branchId 
END; 

回答

3

您可以短路與or運營商搜索的元素:

CREATE PROC [dbo].[RptCashCollectionInner] 
    @branchId int, @searchBy int, @paidDate datetime AS 
BEGIN 
    select Id, from reading 
    where (@searchBy = 1 or [email protected]) and [email protected] 
END; 

或者,更優雅,與in操作:

CREATE PROC [dbo].[RptCashCollectionInner] 
    @branchId int, @searchBy int, @paidDate datetime AS 
BEGIN 
    select Id, from reading 
    where @searchBy in (1, created_by) and [email protected] 
END; 
+0

我真的很喜歡有'IN'運算符的那個。 –

2
CREATE PROC [dbo].[RptCashCollectionInner] 
    @branchId int, @searchBy int, @paidDate datetime AS 
BEGIN 
    select Id from reading 
    where (@searchBy = 1 or [email protected]) and [email protected] 
END;