从CTE更新不会正确更新所有表行。但是更新CTE结果集

时间:2016-05-19 03:00:26

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

我已经购买了CTE,并希望根据CTE的结果更新现有的物理表。

;WITH CTE
 AS 
 (
 Select t.ID As [CTE_ID]
       ,count(distinct case when e.Department='M' then t.ID else null end) as M_Marketing
       ,count(distinct case when e.Department='S' then t.ID else null end) as S_Sales   
       ,count(distinct case when e.Department='U' then t.ID else null end) as U_Utilization    
       ,count(distinct case when e.Department=' ' then t.ID else null end) as No_NoDepartment
    From dbo.Table t (nolock) 
        Left Join dbo.ClearedEmployee ce (nolock) ON t.ID = ce.building_fk
             Join dbo.Employee e (nolock) ON ce.employee_fk = e.employee_pk
    Group By t.ID
)

Select *,  t.ID 
From CTE c (nolock)
FULL JOIN dbo.Table t (nolock) ON t.ID=c.[CTE_ID]
Order By t.ID ASC;

我想用CTE上的每个ID为上面代码生成的结果更新现有表格我正在使用下面的代码:

UPDATE dbo.Table t
    SET Marketing=M_Marketing,
        Sales=S_Sales, 
        Utilization=U_Utilization,
        NoDepartment=No_NoDepartment
    FROM CTE 

但是此代码会更新Marketing,Sales,Utilization和NoDepartment列的所有行(具有唯一ID的所有行),其值将出现在CTE结果集的第一行中。 Basicaly我无法真正使用CTE true结果集来更新表。

1 个答案:

答案 0 :(得分:2)

UPDATE  t
    SET t.Marketing=M_Marketing,
        t.Sales=S_Sales, 
        t.Utilization=U_Utilization,
        t.NoDepartment=No_NoDepartment
    FROM CTE C JOIN Table T ON T.ID=C.CTE_ID

在更新语句中,您需要告诉SQL Server如何将CTE中的数据映射到表中的数据。