As an example in Sql server I can achieve this easily like so:
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
But how do I achieve this in Oracle using a CTE specifically or is there no support for this? I have searched around and havn't found a satisfying answer. Most seem to wrap the CTE in an inline select statement.
Oracle does not allow for directly updating a CTE (unlike SQL Server, which allows it). If I understand your requirement correctly, you want to update the names in the Person
table using the names from the Employee
table, based on matching IDs. One way to do this in Oracle uses a correlated subquery.
UPDATE Person p
SET Name = (SELECT e.Name FROM Employee e
WHERE e.PersonalIdentificationNumber = p.PersonalIdentificationNumber);
Well, as you asked how to use a CTE in UPDATE
, then:
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
);
Though, merge
is somewhat simpler as you don't have to additionally check which rows to update (see the exists
clause in update
example):
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;
However, this can be simplified - see code Ankit posted (but - as I said - if you want to know how to use a CTE, then that's how).
You can use MERGE statement for this -
MERGE INTO Person p
USING Employee e
ON (p.PersonalIdentificationNumber = e.PersonalIdentificationNumber)
WHEN MATCHED THEN
UPDATE
SET p.Name = e.Name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.