Multiple conditional Where clause

后端 未结 2 2002
执笔经年
执笔经年 2021-01-15 18:45

I currently have a query that will pull a bunch of information from my database based on whatever where condition that I want to use.

declare @C         


        
2条回答
  •  终归单人心
    2021-01-15 19:25

    With help from the link that @Norman posted I figured it out. I wanted to post my solution for others to see.

    declare @CaseNum varchar(MAX),
            @ImportId varchar(MAX)
    
    
    set @CaseNum = ''
    set @ImportId = ''
    ----------------------------------------------------------------------------
    
    If(@CaseNum = '')    --Sets the parameter to NULL for COALESCE to work
    Begin
        Select @CaseNum = NULL
    End
    
    If(@ImportId = '')   --Sets the parameter to NULL for COALESCE to work
    Begin
        Select @ImportId = NULL
    End
    
    --------------------
       query in here
    --------------------
    
    where
        gr.[CaseNum] = COALESCE(@CaseNum, gr.[CaseNum])
        and im.ImportId = COALESCE(@ImportId, im.ImportId)
    

    This solution allows the query to use just a single parameter or all at the same time.

提交回复
热议问题