使用CASE WHEN时出现语法错误

时间:2012-12-10 07:13:40

标签: sql-server-2008

我想在SQL Server 2008中where语句的select部分添加一个案例。

SELECT * 
FROM CR_LOAN_DTL 
WHERE 
    LOAN_ID = 1
    AND REFERENCE_NO = CASE 
                          WHEN @i_loan_id = 0 THEN >=1 
                          CASE WHEN  @i_loan_id = 0 THEN REFERENCE_NO  >=1 and REFERENCE_NO  <=9999999999999 
                               ELSE  REFERENCE_NO = @i_loan_id 
                          END 

它给了我一个错误:

  

“&gt;”

附近的语法不正确

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您的CASE语句无法返回>=1的“逻辑”。它需要返回一个值,而不是需要解析的逻辑语句。

选项可以是:

WHERE LOAN_ID=1 AND   
   ((@i_loan_id <> 0 AND REFERENCE_NO = @i_loan_id)
OR (@i_loan_id = 0 AND REFERENCE_NO BETWEEN 1 AND 9999999999999))