SQL Server 2008 R2: Prepare Dynamic WHERE Clause

前端 未结 3 932
你的背包
你的背包 2021-01-17 03:06

I have the following stored procedure with four parameters.

Stored procedure spTest:

CREATE PROCEDURE spTest
    @Name varchar(20) = \'\         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-17 03:52

    You can use ISNULL and NULLIF also in this case:
    below code should work :

    CREATE PROCEDURE spTest
        @Name varchar(20) = '',
        @Address varchar(100) = '',
        @City varchar(50) = '',
        @Pin varchar(50) = ''
    AS
        SET @Name=NULLIF(@Name,'')
        SET @Address=NULLIF(@Address,'')
        SET @City=NULLIF(@City,'')
        SET @Pin=NULLIF(@Pin,'')
    
        SELECT * 
        FROM Test_Table 
        WHERE Name = ISNULL(@Name,Name)
        AND Address = ISNULL(@Address,Address)
        AND City = ISNULL(@City,City)
        AND Pin = ISNULL(@Pin,Pin)
    
    GO
    

提交回复
热议问题