SQL Server 2008 R2: Prepare Dynamic WHERE Clause

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

I have the following stored procedure with four parameters.

Stored procedure spTest:

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


        
3条回答
  •  -上瘾入骨i
    2021-01-17 03:51

    I update the @Zohar answer. Define blank is bad habits, ideally define with null and later use blank. So the query will be

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

    Even I like the @Biswa answer as it use current version of sql server, but Sqlserver 2008R2 does not have this function.

提交回复
热议问题