根据Id将行从一个表更新到另一个表

时间:2014-12-04 03:43:00

标签: sql-server sql-server-2008-r2 sql-update

两个表都有一个client_id列。当client_id列相等时,需要将#LocalDashboardtable中的数据插入到T004_Dashboard中。我已经尝试了这一点,但它确实有助于显示错误"错误的语法附近','。 "

    update T004_Dashboard  set T004_Dashboard.[GrossCharge],T004_Dashboard.[NetCharge] 
= (select #LocalDashboardtable.[GrossCharge] , #LocalDashboardtable.[NetCharge] 
from #LocalDashboardtable   where 
#LocalDashboardtable.client_id =T004_Dashboard.client_id and 
#LocalDashboardtable.[month] =T004_Dashboard.[month] 
and #LocalDashboardtable.[year] =T004_Dashboard.[year]  )

请帮帮我

1 个答案:

答案 0 :(得分:1)

这是您的查询(看起来很像SQL Server):

update T004_Dashboard
    set T004_Dashboard.[GrossCharge],
        T004_Dashboard.[NetCharge] = (select #LocalDashboardtable.[GrossCharge], #LocalDashboardtable.[NetCharge] 
                                      from #LocalDashboardtable
                                      where #LocalDashboardtable.client_id = T004_Dashboard.client_id and 
                                            #LocalDashboardtable.[month] = T004_Dashboard.[month] and
                                            #LocalDashboardtable.[year] = T004_Dashboard.[year]
                                     );

您不能将一对列设置为子查询中的一对列。相反,请使用join

update T004_Dashboard
    set GrossCharge = ld.GrossCharge,
        NetCharge = ld.NetCharge
    from T004_Dashboard d join
         #LocalDashboardtable ld
         on ld.[month] = d.[month] and ld.[year] = d.[year] and
            ld.client_id = d.client_id;

此外,SQL Server不允许update/set语句中的限定列名