我在SQL中有以下SP:
ALTER PROCEDURE [dbo].[search_employee_special]
(
@employeruid uniqueidentifier,
@groupuid uniqueidentifier,
@includedependants bit = 0
)
AS
DECLARE @emptyuid uniqueidentifier
SET @emptyuid = CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
SELECT
emp.id,
emp.name
FROM employee emp
WHERE emp.isactive = 1
AND employeruid = @employeruid
AND (@groupuid = @emptyuid OR emp.gropuid = @groupuid)
使用过滤器效果很好,当@groupuid为空GUID时,它不会按groupuid过滤,否则按groupuid过滤...
现在,我需要的是一点点复杂,因为我必须结合其他参数:
ALTER PROCEDURE [dbo].[search_employee_special]
(
@employeruid uniqueidentifier,
@groupuid uniqueidentifier,
@includedependants bit = 0
)
AS
DECLARE @emptyuid uniqueidentifier
SET @emptyuid = CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
SELECT
emp.id,
emp.name
FROM employee emp
WHERE emp.isactive = 1
AND employeruid = @employeruid
--AND (@groupuid = @emptyuid OR emp.gropuid = @groupuid)
AND (
(@includedependants = 0 AND
(@groupuid = @emptyuid
OR emp.groupuid = @groupuid))
OR emp.specialgroupuid = @groupuid)
这不起作用 ...我需要的是,如果@includedependants = 1则会过滤emp.specialgroupuid,否则会过滤emp.groupuid。
有关如何解决的任何线索?我确信这很简单:)
提前感谢帮助。
答案 0 :(得分:3)
AND (
(
@includedependants = 0 AND
(@groupuid = @emptyuid OR emp.groupuid = @groupuid)
)
OR emp.specialgroupuid = @groupuid
)
OR
部分将始终运行,无论@includedependants
的值是什么,我猜这不是你想要的。你想要的更像是什么;
AND (
(
@includedependants = 0 AND
(@groupuid = @emptyuid OR emp.groupuid = @groupuid)
)
OR
(
@includedependants = 1 AND
emp.specialgroupuid = @groupuid
)
)
答案 1 :(得分:1)
我会用一个案子。不幸的是,所需的语法使它非常难看。
AND 1 = case when @includedependants = 1 then
case when emp.specialgroupuid = @groupuid then 1 else 0 end
else
case when @groupuid = @emptyuid OR emp.groupuid = @groupuid then 1 else 0 end
end