Update with CTE does not recognize column names in

2019-07-24 22:11发布

问题:

I need to update an existing table with data from another. My CTE is giving me correct result, but when I'm trying to update with the CTE SSMS complains on

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

or Invalid column names at the lines below:

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

This is the code:

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:

The correct update statement has only one set. Also, you have no cm in the from clause. I'm going to propose getting rid of the 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;

I don't think the final join is necessary.