sql - 如何在 Oracle 中使用 CTE 更新表
问题描述
作为 Sql server 中的示例,我可以像这样轻松地实现这一点:
WITH cte_person AS
(
SELECT PersonalIdentificationNumber, PersonName
FROM Employee
)
UPDATE Person
SET Person.PersonName = cte.PersonName
FROM cte_person cte
WHERE Person.PersonalIdentificationNumber = cte.PersonalIdentificationNumber
但是我如何在 Oracle 中专门使用 CTE 实现这一点,或者不支持这一点?我四处寻找并没有找到令人满意的答案。大多数似乎都将 CTE 包装在内联选择语句中。
解决方案
好吧,当您问如何在 中使用 CTE 时UPDATE
,那么:
update person p set
p.name = (with cte_person as
(select personalidentificationnumber, name
from employee
)
select c.name
from cte_person c
where c.personalidentificationnumber = p.personalidentificationnumber
)
where exists (select null
from employee e
where e.personalidentificationnumber = p.personalidentificationnumber
);
不过,merge
这有点简单,因为您不必另外检查要更新的行(参见示例中的exists
子句update
):
merge into person p
using (with cte_person as
(select personalidentificationnumber, name
from employee
)
select c.personalidentificationnumber,
c.name
from cte_person c
) x
on (p.personalidentificationnumber = x.personalidentificationnumber)
when matched then update set
p.name = x.name;
但是,这可以简化 - 请参阅 Ankit 发布的代码(但是 - 正如我所说 - 如果您想知道如何使用 CTE,那么就是这样)。