根据输入删除where子句的一部分

时间:2015-07-11 08:49:26

标签: sql sql-server select

我有以下查询,如果created_by = @searchBy的输入为@Searchby,我想省略过滤器1。我怎么能这样做?

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;

2 个答案:

答案 0 :(得分:4)

您可以使用or运算符按元素短路搜索:

CREATE PROC [dbo].[RptCashCollectionInner]
  @branchId int, @searchBy int, @paidDate datetime AS
BEGIN
  select Id, from reading
  where (@searchBy = 1 or created_by=@searchBy) and branch_id=@branchId
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 branch_id=@branchId
END;

答案 1 :(得分:2)

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