CASE语句语法错误

时间:2016-06-01 16:32:47

标签: sql sql-server case

我正在尝试写一个案例陈述,但遇到了一些问题。它正在返回incorrect syntax near '='

SELECT
    customer_name,
    customer_initial_purchase_date,
    customer_purchase_date,
    CASE 'repeat_cust'
        WHEN
            customer_initial_purchase_date = customer_purchase_date
        THEN
            'new_cust'
        ELSE
            'repeat_cust'
    END
FROM
    sales

2 个答案:

答案 0 :(得分:1)

SELECT customer_name
    ,customer_initial_purchase_date
    ,customer_purchase_date
    ,CASE WHEN customer_initial_purchase_date = customer_purchase_date
          THEN 'new_cust'
          ELSE 'repeat_cust'
     END
FROM sales

答案 1 :(得分:0)

看起来您可能会对使用case expressions的两种不同方式感到困惑。一,简称"简单"就像:

CASE <expression> WHEN <match 1> THEN <result 1>
    WHEN <match 2> THEN <result 2>
    ELSE <else result>
END

注意,简单case表达式中没有布尔表达式。当SQL Server看到CASE 'repeat_cust'时,它认为它正在处理简单的case表达式,后来被=符号搞糊涂了。

&#34;搜索&#34;版本是:

CASE WHEN <boolean expression 1> THEN <result 1>
    WHEN <boolean expression 2> THEN <result 2>
    ELSE <else result>
END

简单可以随时重写为搜索,但反之亦然:

CASE WHEN <expression> = <match 1> THEN <result 1>
    WHEN <expression> = <match 2> THEN <result 2>
    ELSE <else result>
END