用where子句从一个表插入另一个表。

问题描述 投票:0回答:1

我试图将表2(pacp2列)中的值插入到表1(pacp列)中,其中两个表的设施_id匹配,表1 pacp列为空。 我得到以下错误。

Msg 4104, Level 16, State 1, Line 5 The multi-part identifier "table1.FACILITYID" could not be bound. Msg 4104, Level 16, State 1, Line 5 The multi-part identifier "table1.pacp" could not be bound.

有谁知道为什么不能使用? 我试过为两个表使用别名,但这不起作用。

INSERT INTO database.dbo.table1 (pacp)
SELECT pacp2
FROM table2 
WHERE database.dbo.table1.facility_id = database.dbo.table2.facility_id 
    AND database.dbo.table1.pacp IS NULL
sql-server-2012 sql-insert
1个回答
0
投票

你的问题描述表明你正在寻找一个 update 而非 insert.

这里有一个使用可更新的cte的选项。

with cte as (
    select t1.pacp, t2.pacp2
    from table1 t1
    inner join table2 t2 on t1.facility_id = t2.facility_id 
    where t1.pacp is null
)
update cte set pacp = pacp2

对于行的 table1 哪儿 pacpnull的值。pacp2table2,使用 facility_id 进行匹配。如果成功,那么它就会在 table1 并设置 pacp 的值,到 pacp2.

© www.soinside.com 2019 - 2024. All rights reserved.