简体   繁体   English

PL/SQL 使用游标重写表中的值

[英]PL/SQL using cursors for rewriting values in table

iam trying to rewrite values in my table with help of cursor but without success.我试图在光标的帮助下重写我的表中的值,但没有成功。 For example in table testik i need to rewrite values 'N' in column alcohol to 'NO'.例如,在表 testik 中,我需要将酒精列中的值“N”重写为“NO”。 Can someone give me some advice?有人可以给我一些建议吗?

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;
/

When i run script it will give back that procedure successfully completed but without change in table testik.当我运行脚本时,它将返回该过程成功完成但表 testik 没有变化。

Very confusing and I can only offer an educated guess.非常混乱,我只能提供一个有根据的猜测。 Your explanation sounds as if you would want to update but your code does actually insert.您的解释听起来好像您想要更新,但您的代码确实插入了。

Maybe what you want to do is actually just:也许您想要做的实际上只是:

UPDATE testik SET alcohol = 'NO' WHERE alcohol = 'N';
COMMIT;

PS: No need for PL/SQL for a simple update. PS:不需要 PL/SQL 进行简单的更新。

As you're learning cursors and stuff, here's one option you might consider.当您学习光标和其他东西时,您可以考虑以下一种选择。

Sample table:样品表:

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

Cursor fetches only rows you're interested in;光标只获取您感兴趣的行; no sense in looping through the whole table if you don't want to do anything with rows whose alcohol column value is different from N .如果您不想对alcohol列值与N不同的行执行任何操作,则循环遍历整个表是没有意义的。

Note that it is declared for update so that you could utilize update with the where current of clause;请注意,它被声明for update ,以便您可以将updatewhere current of子句一起使用; it'll update row you've just fetched.它将更新您刚刚获取的行。

I'm also displaying number of updated rows (you didn't ask for that, but no harm in doing it).我还显示了更新的行数(您没有要求这样做,但这样做没有害处)。

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.

Result:结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM