我是PL / SQL的新手,在一本书中,我发现了这个关于更新游标的例子
declare
cursor c_grade(i_student_id in enrollment.student_id%type,
i_section_id in enrollment.section_id%type
) is
select FINAL_GRADE
from enrollment
where student_id_id = i_student_id
and section_id = i_section_id
for update;
cursor c_enrollment is
select e.student_id, e.section_id
from enrollment enr, section sec
where sec.course_no = 135 and
enr.section_id = sec_section_id;
begin
for r_enroll in c_enrollment loop
for r_grade in c_grade(r_enroll.student_id. r_enroll.section_id) loop
update enrollment
set final_grade = 90
where student_id = r_enroll.student_id
and section_id = r_enroll.section_id;
end loop;
end loop;
end;
我的问题是为什么我需要在这个例子中使用for update游标?与此相比有哪些好处:
for r_enroll in c_enrollment loop
update enrollment
set final_grade = 90
where student_id = r_enroll.student_id
and section_id = r_enroll.section_id;
end loop;
答案 0 :(得分:0)
如评论中所述,FOR UPDATE子句用于锁定SELECT语句中的行,这样其他用户就无法更改这些行(更新,删除等等),直到锁是释放。
一旦发出COMMIT或ROLLBACK语句,锁通常会自动释放。当在来自不同用户的同一组数据上运行大量DML语句时,这尤其有用。例如,您需要在特定时刻更新具有最高ID的行,但在更新行之前,另一行由不同用户使用更高ID更新。
对于您的示例,请使用
for r_grade in c_grade(r_enroll.student_id. r_enroll.section_id) loop
将保证您正在更新您锁定的版本,并且没有其他人在您之前更新它。
您可以使用示例here
找到详细说明答案 1 :(得分:0)
为了详细说明您的问题,Oracle中有两种类型的锁定机制
1) Pessimistic Locking
2) Optimistic Locking
Optimistic locking is generally implemented by developers in the code some timestamp etc phenomena so that at one time only one user at a time can update a particular record.
Pessimistic locking on the other hand (what you have used in the question) is the inbuilt functionality your database is providing to handle locking mechanism automatically.
Let me know if this clears your doubt on this.