SQL Server 2008 R2: Prepare Dynamic WHERE Clause

前端 未结 3 930
你的背包
你的背包 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:58

    It's called catch-all queries and it basically goes like this:

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

    You also might want to read this article about catch all queries

提交回复
热议问题