2

我正在尝试组装一个存储过程以返回一组结果。

在我的页面上,我有三个复选框和一个搜索框。

然后在存储过程中,我有这个:

CREATE Procedure [dbo].[sp_Search]
   @Bool1 bit = NULL, 
   @Bool2 bit = NULL,
   @Bool3 bit = NULL,
   @SearchTerm nvarchar(30)
As
Begin
   Select 
        [CompanyID],
        [CompanyName],
        [Label],
        [Bool1],[Bool2],[Bool3]     
    From [Contract Companies]
    WHERE (CompanyName LIKE @SearchTerm OR [Label] LIKE @SearchTerm) AND
    if(@Bool1 IS NOT NULL)
    [Bool1] = 'True'
    end 

if(@Bool2 IS NOT NULL)
 AND    [Bool2] = 'True'
    end 

if(@Bool3 IS NOT NULL)
AND [Bool3] = 'True'
    end 

类似的事情,这三个布尔值并非始终为真,就在它们的复选框将被选中时。

我怎样才能做到这一点?

提前致谢, Laziale

4

2 回答 2

2

你可以尝试这样的事情:

create procedure [dbo].[sp_Search]
   @Bool1 bit = null, 
   @Bool2 bit = null,
   @Bool3 bit = null,
   @SearchTerm nvarchar(30)
as
begin
   select 
        CompanyID,
        CompanyName,
        Label,
        Bool1,
        Bool2,
        Bool3    
    from Contract Companies
    where (CompanyName like @SearchTerm or Label like @SearchTerm)
        and (Bool1 = @Bool1 or @Bool1 is null)
        and (Bool2 = @Bool2 or @Bool2 is null)
        and (Bool3 = @Bool3 or @Bool3 is null)
end

如果存在,这将获得每个布尔值的匹配记录,否则将获得所有记录。

值得注意的是,这可能不是动态检查值的最佳执行方法,但它们在这里是位(通常没有索引),我认为它非常适合。那篇文章中讨论了替代方案。

于 2013-02-07T22:14:41.550 回答
0

带有CASE表达式的选项

CREATE Procedure [dbo].[sp_Search]
   @Bool1 bit = NULL, 
   @Bool2 bit = NULL,
   @Bool3 bit = NULL,
   @SearchTerm nvarchar(30)
As
Begin
   Select 
        [CompanyID],
        [CompanyName],
        [Label],
        [Bool1],[Bool2],[Bool3]     
    From [Contract Companies]
    WHERE (CompanyName LIKE @SearchTerm OR [Label] LIKE @SearchTerm) AND
          [Bool1] = CASE WHEN @Bool1 IS NOT NULL THEN 'True' ELSE [Bool1] END AND
          [Bool2] = CASE WHEN @Bool2 IS NOT NULL THEN 'True' ELSE [Bool2] END AND
          [Bool3] = CASE WHEN @Bool3 IS NOT NULL THEN 'True' ELSE [Bool3] END 
于 2013-02-07T22:31:57.107 回答