用“IN”谓词在WHERE子句中的CASE语句用于SQL Server(Using an '

2019-10-17 14:28发布

这里有一个SQL查询的作品精绝:

DECLARE @IncludePTO AS CHAR
SET @IncludePTO = 'Y'

SELECT     
   HQCO.HQCo, HQCO.Name, PREH.PRDept, PREH.Craft, HRRM.PositionCode, PRTH.Employee, 
   PREH.LastName, PREH.FirstName, SUM(PRTH.Hours) AS Hrs
FROM PREH 
INNER JOIN HRRM ON PREH.PRCo = HRRM.HRCo AND PREH.Employee = HRRM.HRRef 
INNER JOIN PRTH ON PREH.PRCo = PRTH.PRCo AND PREH.Employee = PRTH.Employee 
INNER JOIN HQCO ON PRTH.PRCo = HQCO.HQCo
WHERE     
    (dbo.PRTH.PREndDate BETWEEN '1/1/2012 00:00:00' AND '1/1/2013 00:00:00')
    AND (PRGroup = 2)
    AND dbo.PRTH.EarnCode IN (1,3,8)
GROUP BY 
    HQCO.HQCo, HQCO.Name, PREH.PRDept, PREH.Craft, 
    HRRM.PositionCode, PRTH.Employee, PREH.LastName, PREH.FirstName

但是,我想使用与所述盒子的“IN”谓词当WHERE子句中..看一看以下修改后的查询:

DECLARE @IncludePTO AS CHAR
SET @IncludePTO = 'Y'

SELECT     
   HQCO.HQCo, HQCO.Name, PREH.PRDept, PREH.Craft, HRRM.PositionCode, PRTH.Employee, 
   PREH.LastName, PREH.FirstName, SUM(PRTH.Hours) AS Hrs
FROM PREH 
INNER JOIN HRRM ON PREH.PRCo = HRRM.HRCo AND PREH.Employee = HRRM.HRRef 
INNER JOIN PRTH ON PREH.PRCo = PRTH.PRCo AND PREH.Employee = PRTH.Employee 
INNER JOIN HQCO ON PRTH.PRCo = HQCO.HQCo
WHERE     
    (dbo.PRTH.PREndDate BETWEEN '1/1/2012 00:00:00' AND '1/1/2013 00:00:00')
    AND (PRTH.PRGroup = 2)
    AND 
       CASE WHEN @IncludePTO = 'Y' THEN dbo.PRTH.EarnCode IN (1,2,3,8,100,110,120,115)
            ELSE dbo.PRTH.EarnCode IN (1,2,3,8)
       END
GROUP BY 
    HQCO.HQCo, HQCO.Name, PREH.PRDept, PREH.Craft, HRRM.PositionCode, PRTH.Employee, 
    PREH.LastName, PREH.FirstName

它似乎并没有工作,一直给我一个语法错误:

消息156,级别15,状态1,行15
附近的关键字“IN”的语法不正确。

任何帮助或指导在指出我错过了什么? 我真的很感激任何帮助/提示..谢谢了,

Franv

Answer 1:

你是对的。 语法是不允许的。 你可以试试:

((@IncludePTO = 'Y' and dbo.PRTH.EarnCode IN (1,2,3,8,100,110,120,115)) or
 (@IncludePTO <> 'Y' and dbo.PRTH.EarnCode IN (1,2,3,8))
)

这可以简化为:

(bo.PRTH.EarnCode IN (1,2,3,8) or (@IncludePTO <> 'Y' and dbo.PRTH.EarnCode IN (100,110,120,115))
)

这假定@IncludePTO永远不能为null。 如果是这样,那么这将必须测试的一部分。

如果你真的想中case语句where子句,你可以这样做:

(CASE WHEN @IncludePTO = 'Y' and dbo.PRTH.EarnCode IN (1,2,3,8,100,110,120,115)
      then 'true'
      when @IncludePTO <> 'Y' and dbo.PRTH.EarnCode IN (1,2,3,8)
      then 'true'
      else 'false'
 end) = 'true'


文章来源: Using an 'IN' predicate with CASE statements in the WHERE clause for SQL Server