gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:31:51 25 4
gpt4 key购买 nike

我使用的是 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。这是我的问题,例如,存储过程将搜索 0 作为 CityId 的项目,为此,它会返回错误的结果。因此,如果能够根据 int 参数的值是否大于 0 来拥有一个动态的 where 子句,那就太好了。

提前致谢

最佳答案

试试这个:

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 ...

关于sql - 在存储过程中构建动态 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11396919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com