我有以下四个参数的存储过程.
存储过程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
解决方法
它被称为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