SQL Server 2008 R2:准备动态WHERE子句

前端之家收集整理的这篇文章主要介绍了SQL Server 2008 R2:准备动态WHERE子句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下四个参数的存储过程.

存储过程spTest:

CREATE PROCEDURE spTest
    @Name varchar(20) = '',@Address varchar(100) = '',@City varchar(50) = '',@Pin varchar(50) = ''
AS
    DECLARE @DynamicWhere varchar(max)
    DECLARE @Query varchar(max)

    /* Here I want to prepare a dynamic where clause for all possibilities */
    SET @Query = 'SELECT * FROM Test_Table '+ @DynamicWhere +'';

    EXECUTE(@Query);
GO

好吧,我正在准备这样:

IF @Name = '' AND @Address = '' AND @City = '' AND @Pin = '' 
BEGIN
     SET @DynamicWhere = '';
END
ELSE IF @Name != '' AND @Address = '' AND @City = '' AND @Pin = '' 
BEGIN
     SET @DynamicWhere = 'Name ='''+@Name+'''';
END
ELSE IF @Name != '' AND @Address != '' AND @City = '' AND @Pin = '' 
BEGIN
     SET @DynamicWhere = 'Name ='''+@Name+''' AND Address ='''+@Address+'''';
END
......
......
Many possibilities

这是正确的方法还是有更好的方法来准备动态WHERE子句?

解决方法

它被称为catch-all查询,它基本上是这样的:
CREATE PROCEDURE spTest
    @Name varchar(20) = '',@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

您也可以阅读this article about catch all queries

猜你在找的MsSQL相关文章