我正在尝试组装存储过程以返回一组结果。
在我的页面上,我有三个复选框和一个搜索框。
然后在存储过程中,我有这个:
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
答案 0 :(得分: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
这将获得每个bool存在时的匹配记录,否则将获得所有记录。
注意到这may not be the best performing method动态检查值,但它们是位(often not indexed),我认为它非常优雅。该文章中讨论了备选方案。
答案 1 :(得分: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