在存储过程中构建动态WHERE子句

时间:2012-07-09 14:18:48

标签: sql sql-server sql-server-2008 stored-procedures

我正在使用SQL Server 2008 Express,并且我有一个基于参数从表中执行SELECT的存储过程。我有nvarchar个参数和int个参数。

这是我的问题,我的where子句如下所示:

WHERE [companies_SimpleList].[Description] Like @What 
    AND companies_SimpleList.Keywords Like @Keywords
    AND companies_SimpleList.FullAdress Like @Where
    AND companies_SimpleList.ActivityId = @ActivityId
    AND companies_SimpleList.DepartementId = @DepartementId
    AND companies_SimpleList.CityId = @CityId

此参数是我的ASP.NET MVC 3应用程序的用户设置的过滤器值,并且可能未设置int参数,因此它们的值将为0.这是我的问题,存储过程例如,会搜索0CityId的项目,为此,它会返回错误的结果。因此,如果int参数的值大于0,那么能够拥有动态where子句会很好。

提前致谢

3 个答案:

答案 0 :(得分:35)

请改为尝试:

WHERE 1 = 1
AND (@what     IS NULL OR [companies_SimpleList].[Description] Like @What )
AND (@keywords IS NULL OR companies_SimpleList.Keywords        Like @Keywords)
AND (@where    IS NULL OR companies_SimpleList.FullAdress      Like @Where)
...

如果将任何参数@what@where发送到具有NULL值的存储过程,则将忽略该条件。您可以使用0而不是null作为测试值,然后它将类似于@what = 0 OR ...

答案 1 :(得分:4)

尝试类似

的内容
AND companies_SimpleList.CityId = @CityId or @CityID = 0

答案 2 :(得分:1)

这是另一个易于阅读的SQL Server> = 2008

解决方案
CREATE PROCEDURE FindEmployee
    @Id INT = NULL,
    @SecondName NVARCHAR(MAX) = NULL
AS 
    SELECT  Employees.Id AS "Id",
            Employees.FirstName AS "FirstName",
            Employees.SecondName AS "SecondName"
    FROM Employees
    WHERE Employees.Id = COALESCE(@Id, Employees.Id)
    AND Employees.SecondName LIKE COALESCE(@SecondName, Employees.SecondName) + '%'