如果值不为空,则仅添加搜索条件附加到WHERE子句

时间:2016-08-11 02:40:31

标签: sql vb.net

在网络应用程序中,如果值不为空,我可以这样做以包括搜索条件。

Dim sQuery as string = SELECT * FROM MERCHANT_CATEGORY WHERE 1=1 
If sCatDesc <> "" Then sQuery  &= "AND CAT_DESC LIKE '%' + @CAT_DESC + '%' "

在SQL查询中,如何做到如上?以下是我使用的查询

SELECT * FROM MERCHANT_CATEGORY WHERE 1=1
AND CAT_DESC LIKE  '%' + @CatDesc + '%'

如果@CatDesc是一个空字符串值,并且我的一个记录CAT_DESC为null,则结果将显示那些没有空值的记录。

4 个答案:

答案 0 :(得分:1)

您可以使用以下形式的查询:

SELECT * 
FROM MERCHANT_CATEGORY 
WHERE ((@CatDesc IS NULL) OR (CAT_DESC LIKE '%' + @CatDesc + '%'))

请注意,您不再需要1=1

答案 1 :(得分:0)

你可以试试这个。

select * from table 
where (CAT_DESC like '%'+@CATDESC+"%" and @CATDESC is not null  ) 
or 
(CAT_DESC is null or CAT_DESC="" and @CATDESC is null )

答案 2 :(得分:0)

select *
from table
where cat_desc like '%' + isnull(@catdesc, '') + '%'

答案 3 :(得分:0)

我们可以将ifif评估添加到where子句吗?

对于Eg

    Select * from table 
    where cat_desc like 
         (iif(@cat_desc is not null,"@cat_desc", "'*' or cat_desc is null")

这将向where子句抛出适当的字符串值。

即。如果@cat_desc不为null,则它将获取所有匹配的记录,如果@cat_desc为null,则它将评估字符串--- cat_desc,如&#39; *&#39;或cat_desc为空