Microsoft SQL Server Management Studio中CTE的语法

时间:2019-03-29 14:55:04

标签: sql-server

;WITH 
cte_REFERRALS_REPORTS (referralnum, refer_from, refer_from_name, refer_from_id, refer_to, refer_to_name, refer_to_id)
AS
    (
    SELECT 
        referralnum, refer_from,
        CASE
                WHEN refer_from_id = 'R'    THEN RdicF.refname 
                WHEN refer_from_id = 'P'    THEN PdicF.provname END AS refer_from_name,
        refer_from_id, refer_to, 
        CASE
                WHEN refer_to_id = 'R'      THEN RdicT.refname
                WHEN refer_to_id = 'P'      THEN PdicT.provname END AS refer_to_name,
        refer_to_id
    FROM 
        referral_t r
    LEFT JOIN 
        refcode_t RdicF
    ON  r.refer_from = CASE WHEN r.refer_from_id='R' THEN RdicF.refcode ELSE NULL END
    LEFT JOIN 
        refcode_t RdicT
    ON  r.refer_to = CASE WHEN r.refer_to_id = 'R' THEN RdicT.refcode ELSE NULL END
    LEFT JOIN
        provcode_t PdicF
    ON r.refer_from  = CASE WHEN r.refer_from_id = 'P' THEN PdicF.provcode ELSE NULL END
    LEFT JOIN
        provcode_t PdicT
    ON r.refer_to = CASE WHEN r.refer_to_id = 'P' THEN PdicT.provcode ELSE NULL END
    )

我在CTE内的查询有效,但是我感觉语法错误。我不断收到此错误:

  

“')'附近的语法不正确”

请帮助。我是SQL和编码的新手。我正在努力使用CTE和Window函数。

1 个答案:

答案 0 :(得分:4)

您缺少使用CTE的SELECT(或UPDATE,DELETE或INSERT)。声明声明中不会使用的CTE没有意义。

WITH 
cte_REFERRALS_REPORTS (referralnum, refer_from, refer_from_name, refer_from_id, refer_to, refer_to_name, refer_to_id)
AS
    (
    SELECT 
        referralnum, refer_from,
        ISNULL( RdicF.refname, PdicF.provname) END AS refer_from_name, --Code shortened, but you could keep the original for clarity.
        refer_from_id, refer_to, 
        CASE
                WHEN refer_to_id = 'R'      THEN RdicT.refname
                WHEN refer_to_id = 'P'      THEN PdicT.provname END AS refer_to_name,
        refer_to_id
    FROM      referral_t r
    LEFT JOIN refcode_t RdicF ON  r.refer_from = RdicF.refcode  AND r.refer_from_id = 'R'
    LEFT JOIN refcode_t RdicT ON  r.refer_to   = RdicT.refcode  AND r.refer_to_id = 'R'
    LEFT JOIN provcode_t PdicF ON r.refer_from = PdicF.provcode AND r.refer_from_id = 'P'
    LEFT JOIN provcode_t PdicT ON r.refer_to   = PdicT.provcode AND r.refer_to_id = 'P'
    )
SELECT *
FROM cte_REFERRALS_REPORTS;

我对您的代码进行了一些更改,这些更改可能有助于开发人员和优化程序了解这些JOINS上发生的事情。您还需要了解,分号(;)是语句终止符,应位于每个语句的末尾,而不是CTE的开始。