我有一个带有两个参数的存储过程,这将向我返回员工列表。我的存储过程运行良好,但是我需要根据条件将条件放入where子句中。以下是我的存储过程:
create procedure sp_GetEmployees
@BranchId int = 0,
@DeptId int = 0
as
Begin
if(@BranchId > 0 and @DeptId > 0)
select * from Employees where BranchId = @BranchId and DeptId = @DeptId
else if (@BranchId > 0 and @DeptId = 0)
select * from Employees where BranchId = @BranchId
else if (@BranchId > 0 and @DeptId = 0)
select * from Employees where DeptId = @DeptId
else
select * from Employees
End
这是简单的情况,但是在更复杂的情况下,我要传递8到10个参数,并且为它们设置条件将是一件令人头疼的事情。我需要在一个select语句中简化它。我尝试了以下方法,但是当然这是不正确的:
if(@BranchId > 0 or @DeptId > 0)
select * from Employees where
case @BranchId when 0 then ''
else BranchId = @BranchId
End
else
select * from Employees
如何简化它?
答案 0 :(得分:1)
您可以像下面这样简化查询。
SELECT *
FROM Employee
WHERE ( Branchid = @BranchId
OR @BranchId = 0 )
AND ( Deptid = @DeptId
OR @DeptId = 0 )
答案 1 :(得分:1)
我会这样做,将OPTION (RECOMPILE)
添加到您的查询中;这意味着将不会使用任何缓存的查询计划,因为它们对一组不同的参数可能毫无用处(这是一个万能的查询):
CREATE PROCEDURE sp_GetEmployees @BranchId int = 0,
@DeptId int = 0
AS
BEGIN
SELECT *
FROM Employees
WHERE (BranchId = @BranchId
OR @BranchId = 0)
AND (DeptId = @DeptId
OR @DeptId = 0)
OPTION (RECOMPILE);
END;
您正尝试将CASE
表达式用作语句,并非如此。
答案 2 :(得分:1)
您可以执行以下操作:
WHERE (@Parameter1 = 0 OR Field1=@Parameter1)
AND (@Parameter2 = 0 OR Field2=@Parameter2)
AND ...
答案 3 :(得分:0)
您可以通过这种方式将查询与条件检查连接起来:
ALTER PROCEDURE [dbo].[Your stored procedure name]
@aaa INT condition parameter,
@bbb INT condition parameter,
@ccc INT condition parameter,
@RecordCount INT OUTPUT
AS
Declare @aaa nvarchar(500)
Declare @bbb nvarchar(500)
Declare @ccc nvarchar(500)
BEGIN
BEGIN TRY
SET @qry = N'SELECT <here your query> where 1=1
'
IF @aaa= 0
BEGIN
SET @aaa = ''
END
ELSE
BEGIN
SET @aaa = ' and p.userid = '+CONVERT(varchar(5),@aaa)+' '
END
IF @bbb= 0
BEGIN
SET @bbb = ''
END
ELSE
BEGIN
SET @bbb = ' and p.Senderid = '+CONVERT(varchar(10),@bbb)+' '
END