[英]PL/SQL using cursors for rewriting values in table
我試圖在光標的幫助下重寫我的表中的值,但沒有成功。 例如,在表 testik 中,我需要將酒精列中的值“N”重寫為“NO”。 有人可以給我一些建議嗎?
DECLARE
CURSOR kurzor IS SELECT * FROM testik ORDER BY datum DESC;
ttest kurzor%ROWTYPE;
BEGIN
FOR ttest IN kurzor LOOP
IF (ttest.alcohol = 'N') THEN
INSERT INTO testik(alcohol) VALUES ('NO');
END IF;
END LOOP;
END;
/
當我運行腳本時,它將返回該過程成功完成但表 testik 沒有變化。
非常混亂,我只能提供一個有根據的猜測。 您的解釋聽起來好像您想要更新,但您的代碼確實插入了。
也許您想要做的實際上只是:
UPDATE testik SET alcohol = 'NO' WHERE alcohol = 'N';
COMMIT;
PS:不需要 PL/SQL 進行簡單的更新。
當您學習光標和其他東西時,您可以考慮以下一種選擇。
樣品表:
SQL> select * from testik;
ID ALC
---------- ---
1 Y
2 N --> should be updated to NO
3 YES
4 NO
5 N --> should be updated to NO
光標只獲取您感興趣的行; 如果您不想對alcohol
列值與N
不同的行執行任何操作,則循環遍歷整個表是沒有意義的。
請注意,它被聲明for update
,以便您可以將update
與where current of
子句一起使用; 它將更新您剛剛獲取的行。
我還顯示了更新的行數(您沒有要求這樣做,但這樣做沒有害處)。
SQL> set serveroutput on;
SQL> declare
2 cursor c1 is select id, alcohol
3 from testik
4 where alcohol = 'N'
5 order by id
6 for update;
7 c1r c1%rowtype;
8 l_cnt number := 0;
9 begin
10 open c1;
11 loop
12 fetch c1 into c1r;
13 exit when c1%notfound;
14
15 update testik set
16 alcohol = 'NO'
17 where current of c1;
18 l_cnt := l_cnt + 1;
19 end loop;
20 close c1;
21 dbms_output.put_line('Updated ' || l_cnt || ' row(s)');
22 end;
23 /
Updated 2 row(s)
PL/SQL procedure successfully completed.
結果:
SQL> select * from testik;
ID ALC
---------- ---
1 Y
2 NO
3 YES
4 NO
5 NO
SQL>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.