在SQL

时间:2016-12-13 04:33:04

标签: sql sql-server

我有这样的查询:

SELECT  
    CASE 
       WHEN (CONVERT(INT, (datepart(DD, A.CIDATE))) AND Year(getDate()) = 2016 ) <= 15
          THEN CONVERT(INT,(datepart(MM,A.CIDATE)))  
       WHEN CONVERT(INT, (datepart(DD, A.CIDATE))) > 15
          THEN CONVERT(INT, (datepart(MM, A.CIDATE))) + 1
       ELSE 0
    END AS MASA_PAJAK
FROM
    V_CLAIM_INTERNAL A

它正在工作但是当我添加 AND年(getDate())= 2016 时,它会抛出错误:

  

Msg 4145,Level 15,State 1,Line 1
  在预期条件的上下文中指定的非布尔类型的表达式,接近&#39; AND&#39;。

我也尝试转换,但仍然有同样的错误。

  SELECT 
      CASE 
         WHEN ((CONVERT(INT, (datepart(DD, A.CIDATE))) AND (convert(int, Year(getDate()) = 2016 ))) <= 15  
            THEN CONVERT(INT, (datepart(MM, A.CIDATE))) 
         WHEN CONVERT(INT, (datepart(DD, A.CIDATE))) > 15 
            THEN CONVERT(INT, (datepart(MM, A.CIDATE))) + 1 
         ELSE 0  
      END AS MASA_PAJAK
  FROM         
      V_CLAIM_INTERNAL A

我的查询错误是什么:?

3 个答案:

答案 0 :(得分:2)

这可能是你打算做的事情:

SELECT CASE WHEN DATEPART(DD, A.CIDATE) <= 15 AND YEAR(GETDATE()) = 2016
            THEN DATEPART(MM, A.CIDATE)
            WHEN DATEPART(DD, A.CIDATE) > 15
            THEN DATEPART(MM, A.CIDATE) + 1
            ELSE 0
       END AS MASA_PAJAK
FROM V_CLAIM_INTERNAL A

请注意,需要转换/转换调用DATEPART的结果,因为它已经返回一个整数。

答案 1 :(得分:0)

SELECT  CASE 
            WHEN (CONVERT(INT,(datepart(DD,A.CIDATE)))<= 15 AND Year(getDate()) = 2016 )   THEN  CONVERT(INT,(datepart(MM,A.CIDATE)))  
            WHEN  CONVERT(INT,(datepart(DD,A.CIDATE))) > 15 THEN CONVERT(INT,(datepart(MM,A.CIDATE)))+1
        ELSE 0  END AS MASA_PAJAK
FROM    V_CLAIM_INTERNAL A

答案 2 :(得分:0)

尝试此查询:

SELECT  CASE WHEN datepart(DD,A.CIDATE)<= 15 AND
              Year(getDate()) = 2016 
         THEN datepart(MM,A.CIDATE)
         WHEN datepart(DD,A.CIDATE) > 15
         THEN datepart(MM,A.CIDATE) + 1
         ELSE 0
    END AS MASA_PAJAK
FROM V_CLAIM_INTERNAL A