首页 > 解决方案 > 更新语句给出表别名错误

问题描述

我无法弄清楚以下语法有什么问题。

alter table #table1 add C21 datetime
update #table1 a
set a.C21 = b.C21_result_lab from #table2 b where a.person_id = b.person_id and 
a.source_id = b.source_id

错误信息:

消息 102,级别 15,状态 1,第 363 行“a”附近的语法不正确。

标签: sqlsql-servertsqljoinsql-update

解决方案


这是正确的语法:

alter table #table1 add C21 datetime;
update a
set a.C21 = (
  select b.C21_result_lab from #table2 b 
  where 
    a.person_id = b.person_id 
    and 
    a.source_id = b.source_id
)
from #table1 a

您必须确保选择查询返回的行数不超过 1。
或者您可以通过加入来做到这一点:

update a
set a.C21 = b.C21_result_lab 
from #table1 a inner join #table2 b 
on a.person_id = b.person_id and a.source_id = b.source_id

推荐阅读