I need to update several columns of a table, but one piece of information is stored in another table, so I'm assuming I need to join them but I'm unsure how to. Basically I need to update the job title where the office is T06 and the start date where the original start_date was '05-FEB-09, 08:00' for the staff whose last name is Parker
So far I have:
UPDATE JOB
SET JOB_TITLE = 'Head of Technology'
WHERE OFFICE = 'T06'
AND SET START_DATE = '26-JUN-17, 08:00'
WHERE START_DATE = '05-FEB-09, 08:00'
FROM JOB
JOIN STAFF
ON JOB.STAFF_ID = STAFF.STAFF_ID
WHERE STAFF.LAST_NAME = 'Parker';
Correct syntax would be
update job
set job_title = 'Head of Technology',
start_date = '26-JUN-17, 08:00'
where office = 'T06'
and start_date = '05-FEB-09, 08:00'
and staff_id =(select staff_id
from staff
where last_name = 'Parker'
);
However, it might need to be modified ( START_DATE
condition is strange).
Also, it is unclear what START_DATE
datatype is. Should be DATE
, but your code suggests a string ( VARCHAR2
).
Alternative #1 (note TO_DATE
) function:
update job
set job_title = 'Head of Technology',
start_date = to_date('26-JUN-17, 08:00', 'dd-mon-yy, hh24:mi')
where office = 'T06'
and start_date = to_date('05-FEB-09, 08:00', 'dd-mon-yy, hh24:mi')
and staff_id =(select staff_id
from staff
where last_name = 'Parker'
);
Alternative #2 (note CASE
and absence of START_DATE
in WHERE
clause):
update job
set job_title = 'Head of Technology',
start_date = case when start_date = to_date('05-FEB-09, 08:00', 'dd-mon-yy, hh24:mi')
then to_date('26-JUN-17, 08:00', 'dd-mon-yy, hh24:mi')
else start_date
end
where office = 'T06'
and staff_id =(select staff_id
from staff
where last_name = 'Parker'
);
I would use EXISTS
:
UPDATE JOB
SET JOB_TITLE = 'Head of Technology'
OFFICE = 'T06',
START_DATE = '26-JUN-17, 08:00'
WHERE START_DATE = '05-FEB-09, 08:00' AND
OFFICE = 'T06' AND
EXISTS (SELECT 1
FROM STAFF
WHERE JOB.STAFF_ID = STAFF.STAFF_ID AND
STAFF.LAST_NAME = 'Parker'
);
The most native way is to use updatable join view
Simple make you join and select all relevant columns, than add UPDATE
modifying the join.
update (
select job.*
FROM JOB
JOIN STAFF
ON JOB.STAFF_ID = STAFF.STAFF_ID
WHERE STAFF.LAST_NAME = 'Parker')
set JOB_TITLE = 'Head of Technology',
START_DATE = '26-JUN-17, 08:00'
The only requirement is that the column STAFF_ID
in STAFF
table is backed with a unique index (eg primary key).
Without this you get the ERROR ORA-01779: cannot modify a column which maps to a non key-preserved table
This way of UPDATE
is very usefull if you need to update with a value from the joined table (not your case).
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.