[英]What's the point of parameterized cursors in PL/SQL?
有人能解釋一下在 PL/SQL 中使用參數化游標而不是僅僅創建一個變量並在內部使用它的意義何在?
以下匿名塊顯示了我的意思:
DECLARE
num NUMBER := 1;
CURSOR d1 (p_num IN NUMBER) IS SELECT 'foo' FROM dual WHERE 1 = p_num;
CURSOR d2 IS SELECT 'foo' FROM dual WHERE 1 = num;
BEGIN
NULL;
END;
游標 d1 和 d2 之間在處理/性能/等方面有什么不同嗎?
提前致謝。
您可能直到運行時才知道您的p_num
值。 它可能是您從其他處理、另一個表、客戶端環境或以某種方式計算得到的東西。
作為一個簡單的例子:
declare
cursor c1 is
select * from departments;
cursor c2 (p_department_id employees.department_id%type) is
select * from employees
where department_id = p_department_id;
begin
for r1 in c1 loop
-- do something with this department info
dbms_output.put_line(r1.department_name);
-- now loop through empoyees in that department
for r2 in c2 (r1.department_id) loop
-- do something with this employee info
dbms_output.put_line(' ' || r2.first_name);
end loop;
end loop;
end;
/
Administration
Jennifer
Marketing
Michael
Pat
Purchasing
Den
Alexander
...
c2
游標正在尋找單個部門中的員工,但不能進行硬編碼。
您可以使用d2
構造的等效項執行相同的操作,即分配一個單獨的局部變量,內部游標仍將使用該變量 - 因為它正在重新打開並在此時評估變量:
declare
l_department_id departments.department_id%type;
cursor c1 is
select * from departments;
cursor c2 is
select * from employees
where department_id = l_department_id;
begin
for r1 in c1 loop
-- do something with this department info
dbms_output.put_line(r1.department_name);
-- ...
-- now loop through empoyees in that department
l_department_id := r1.department_id;
for r2 in c2 loop
-- do something with this employee info
dbms_output.put_line(' ' || r2.first_name);
end loop;
end loop;
end;
/
...但有一個參數可以更清楚地表明該值預計會發生變化,並避免了兩次調用而忘記更改中間值的可能性。
在這兩種情況下,游標查詢的實際 SQL 將被視為具有綁定變量; 不同之處在於它是如何填充的。
很明顯,您不會真正使用嵌套循環或任何 PL/SQL 來執行此特定任務; 並且在很多地方使用這種構造也同樣適用,或者查詢至少可以通過連接組合成單個游標。
對於更復雜的邏輯,它仍然很有用,例如,代碼可以采用多條路徑和多個可選的輔助游標,並且都需要來自相同(昂貴)基本查詢的信息,並且您不想重復加入到基表。
與大多數逐行處理一樣,我懷疑它被濫用的頻率比真正必要的要高。 盡管如此,它仍然是一個有用的工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.