一尘不染

从选择SQL服务器更新

sql

按照[这篇文章](https://codingdict.com/questions/214492)的答案,我有这样的事情:

update MyTable
set column1 = otherTable.SomeColumn,
    column2 = otherTable.SomeOtherColumn
from MyTable
inner join
(select *some complex query here*) as otherTable
on MyTable.key_field = otherTable.key_field;

但是,我不断收到此错误:

列前缀“ otherTable”与查询中使用的表名或别名不匹配。

我不知道怎么了。我不能从这样的选择查询中进行这样的更新吗?任何帮助将不胜感激。

(我正在使用* blush * sql server2000。)

编辑:

这是实际的查询

update pdx_projects set pr_rpc_slr_amount_year_to_date = summary.SumSLR, pr_rpc_hours_year_to_date = summary.SumHours
    from pdx_projects pr join (
select  pr.pr_pk pr_pk, sum(tc.stc_slr_amount)  SumSLR, sum(tc.stc_worked_hours)  SumHours from pdx_time_and_cost_from_rpc tc 
    join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
    join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
    join pdx_projects pr on pr_pk = sl.pr_fk
    where tc.stc_time_card_year = year(getdate())
    group by pr_pk
) as summary

on pr.pr_pk = summary.pr_pk

而实际的错误消息是

服务器:消息107,级别16,状态2,行1列前缀“摘要”与查询中使用的表名或别名不匹配。


阅读 142

收藏
2021-05-16

共1个答案

一尘不染

我向您提交此更改后的查询:

update x
set x.pr_rpc_slr_amount_year_to_date = summary.sumSLR, 
    x.pr_rpc_hours_year_to_date = summary.sumHours
from pdx_projects x
join (
    select  pr.pr_pk as pr_pk, 
            sum(tc.stc_slr_amount) as SumSLR, 
            sum(tc.stc_worked_hours) as SumHours 
    from pdx_time_and_cost_from_rpc tc 
    join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
    join pdx_rpc_links sl on sp.sol_pk = sl.sol_fk
    join pdx_projects pr on sl.pr_fk = pr.pr_pk
    where tc.stc_time_card_year = year(getdate())
    group by pr.pr_pk
) as summary
on x.pr_pk = summary.pr_pk

此处明显不同:我不在pr复杂查询的内部和外部重复使用别名。我按照自己喜欢的方式对连接进行了重新排序(首先引用了表,然后在2个地方显式标记了pr_pk)。我还更改了使用的更新语法update<alias>

2021-05-16