在使用CASE的UPDATE语句中使用CTE

时间:2014-02-05 21:44:55

标签: sql sql-server tsql

我有以下代码:

WITH CTE_List AS
(
SELECT B.Chain_Code, B.State
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbo.StateChain_List AS B
ON A.State = B.State
AND A.Chain_Code = B.Chain_Code
)

UPDATE Company.dbo.Company_Master
SET MFN_Ind = (
    CASE
        WHEN (CTE_List.Chain_Code IS NULL) AND (CTE_List.State IS NULL) THEN 'N'
        ELSE 'Y'
    END
)
FROM CTE_List

CTE_List中的select语句返回这样的值,但对应于Company_Master表中的每条记录:

Chain_Code | State
00992      | IL
NULL       | NULL
NULL       | NULL
00732      | MA
NULL       | NULL

我的最终目标是根据此CTE_List更新Company.dbo.Company_Master中的MFN_Ind列。如果填充了Chain_Code和State,则MFN_Ind ='Y'。如果Chain_Code和State为NULL,则MFN_Ind ='N'。

现在设置,查询更新MFN_Ind列,所有内容都设置为'Y',因此CASE的第一部分显然没有捕获NULL字段。有关如何解决此问题的任何提示?

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为你使这个变得比它需要的复杂得多。

UPDATE m
  SET m.MFN_Ind = CASE WHEN l.State IS NULL THEN 'N' ELSE 'Y' END
FROM Company.dbo.Company_Master AS m
LEFT OUTER JOIN Company.dbo.StateChain_List AS l
ON m.State = l.State
AND m.Chain_Code = l.Chain_Code;

或者最好将其拆分为2 - 将所有行更新为N,然后将匹配的行更新为Y

UPDATE Company.dbo.Company_Master SET m.MFN_Ind = 'N';

UPDATE m SET m.MFN_Ind = 'Y'
FROM Company.dbo.Company_Master AS m
WHERE EXISTS (SELECT 1 FROM Company.dbo.StateChain_List AS l
WHERE m.State = l.State
AND m.Chain_Code = l.Chain_Code);

答案 1 :(得分:0)

    WITH CTE_List AS
    (
    SELECT B.Chain_Code, B.State
    FROM Company.dbo.Company_Master AS A
    LEFT OUTER JOIN Company.dbo.StateChain_List AS B
    ON A.State = B.State
    AND A.Chain_Code = B.Chain_Code
    )

    ---UPDATE THE RECORD

    UPDATE m
    SET MFN_Ind = (
        CASE WHEN (CTE.Chain_Code IS NULL) AND (CTE.State IS NULL) THEN 'N'
            ELSE 'Y'
        END
    )
    FROM CTE_List cte 
  INNER JOIN  Company.dbo.Company_Master m 
    on m.State =cte.state