用存储过程中的几个参数搜索可能为空

时间:2018-09-04 15:01:37

标签: sql sql-server stored-procedures

我创建了一个搜索器,如下所示:

create procedure [dbo].[search_pazhoheshgar]
    @se_code_melli varchar(10) = NULL,
    @se_name nvarchar(30) = NULL,
    @se_family nvarchar(30) = NULL,
    @se_name_uni nvarchar(100) = NULL,
    @se_name_reshte_tahsili nvarchar(50) = NULL
as
begin try
begin tran
    set nocount on;

    select 
        sabt.code_melli, sabt.name, sabt.family, 
        sabt_como_univercity.name_uni,
        sabt_como_reshte.name_reshte_tahsili
    from 
        sabt 
    inner join 
        sabt_como_univercity on sabt.univercity = sabt_como_univercity.id_uni
    inner join 
        sabt_como_reshte on sabt.name_reshte = sabt_como_reshte.id_reshte_tahsili
    where 
        @se_code_melli is not null
        and @se_code_melli <> '' 
        and sabt.code_melli like '%' + @se_code_melli + '%' 
         or @se_name is not null 
        and @se_name <> ''  
        and sabt.name like '%' + @se_name + '%' 
         or @se_family is not null
        and @se_family <> '' 
        and sabt.family like '%' + @se_family + '%' 
         or @se_name_uni is not null 
        and @se_name_uni <> '' 
        and sabt_como_univercity.name_uni like '%' + @se_name_uni + '%' 
         or @se_name_reshte_tahsili is not null
        and @se_name_reshte_tahsili <> '' 
        and sabt_como_reshte.name_reshte_tahsili like '%' + @se_name_reshte_tahsili + '%'

    commit tran
end try
begin catch
    rollback tran
    return -1
end catch

当我使用参数搜索时,这不是问题。但是,当我设置多个参数时,最后输入的参数将作为搜索条件。 显然,此问题是由于OR的存在。现在,如果我使用AND而不是OR,则我将不能放置NULL值,因为搜索无效。我该怎么办?

2 个答案:

答案 0 :(得分:1)

我相信您想要的逻辑是:

WHERE (@se_code_melli IS NULL OR sabt.code_melli LIKE '%' + @se_code_melli + '%') AND 
      (@se_name IS NULL OR sabt.name like '%' + @se_name + '%') AND
       . . .

也就是说,检查是否为条件匹配的参数为NULL OR 。然后通过 AND 将这些条件联系起来。

答案 1 :(得分:1)

我将首先使用括号,因为您不清楚要实现什么。您是否要返回所有在列中至少找到一个值的记录?

WHERE
(COALESCE(@se_code_melli,'') != '' AND  sabt.code_melli LIKE '%' + @se_code_melli + '%') OR 
(COALESCE(@se_name,'') != '' AND sabt.name like '%' + @se_name + '%') OR  
(COALESCE(@se_family,'') != '' AND sabt.family like '%' + @se_family + '%') OR
(COALESCE(@se_name_uni,'') != '' AND sabt_como_univercity.name_uni like '%' + @se_name_uni + '%') OR
(COALESCE(@se_name_reshte_tahsili,'') != '' AND sabt_como_reshte.name_reshte_tahsili like '%' + @se_name_reshte_tahsili + '%')