0

我在 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。

关于如何解决它的任何线索?我敢肯定它很简单:)

提前感谢帮助。

4

2 回答 2

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
     )
    )
于 2013-06-28T22:58:56.020 回答
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
于 2013-06-28T23:00:16.730 回答