使用CTE更新无法识别set子句中的列名

时间:2016-06-14 00:10:13

标签: sql sql-server sql-update common-table-expression

我需要用另一个表中的数据更新现有表。我的CTE正在给我正确的结果,但是当我试图用CTE SSMS更新时会抱怨

Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '.'. 

或以下行中的列名无效:

set cm.Action.Identifier_fk = ID
set cm.ActionRequestedAction = Action
set cm.Action.apartment_fk = apartment_fk

这是代码:

Use DB;
GO

with CTE (ID,Action,Identifier_fk,apartment_fk) AS 

(select a.ID, a.Action, b.Identifier_fk, m.apartment_fk 
from Project.AllSent a (nolock) 
    left outer join cm.Action b (nolock) on a.ID=b.Identifier_fk
    left Outer Join csv.Matching m (nolock) on m.Identifier_fk = a.ID
    left outer join csv.Apartment p (nolock) on m.apartment_fk=p.apartment_pk
    where b.Identifier_fk is NULL) 

update cm.Action 
set cm.Action.Identifier_fk = ID
set cm.Action.RequestedAction = Action
set cm.Action.apartment_fk = apartment_fk

    from CTE c
    JOIN Project.AllSent t (nolock) on t.ID=c.ID;

1 个答案:

答案 0 :(得分:0)

正确的update语句只有一个set。此外,cm子句中没有from。我打算建议摆脱CTE:

update b
    set Identifier_fk = a.ID,
        Action.RequestedAction = a.Action,
        apartment_fk = mm.apartment_fk
    from Project.AllSent a (nolock) left join
         cm.Action b (nolock)
         on a.ID = b.Identifier_fk left join
         csv.Matching m (nolock)
         on m.Identifier_fk = a.ID left join
         csv.Apartment p (nolock)
         on m.apartment_fk = p.apartment_pk
    where b.Identifier_fk is NULL;

我认为最终join是必要的。