在Oracle中更新列值的过程

时间:2014-12-06 15:55:32

标签: oracle loops stored-procedures plsql

使用Oracle中的过程我想从输入参数更新表中所有记录的代码字段。例如,如果参数值为100:

第1行,代码256更改为101
代码为368的第2行更改为102
代码为624的第3行更改为103

我试试这个

create or replace PROCEDURE procedure_name (parameter_newcode code%TYPE) AS
 CURSOR cursor_name IS select code from table
                           order by code asc;
  var_newCode code%TYPE;
  BEGIN
  OPEN cursor_name;
  LOOP
  FETCH cursor_name INTO var_newCode;
  EXIT WHEN cursor_name%NOTFOUND;
  var_newCode:=parameter_newcode+1;
  update table set code = var_newCode;
  END LOOP;
  CLOSE cursor_name;
 END procedure_name;

但每行返回相同的代码(例如,如果参数为100 - > 101)

1 个答案:

答案 0 :(得分:2)

在每个循环中设置(一次又一次)
var_newCode:=parameter_newcode+1;
并且您没有指定要更新的记录
update table set code = var_newCode;

一些事情

create or replace PROCEDURE procedure_name (parameter_newcode code%TYPE) AS
 CURSOR cursor_name IS select code from myTable
                           order by code asc;
  var_oldCode code%TYPE;
  var_newCode code%TYPE;
  BEGIN
  var_newCode:=parameter_newcode;
  OPEN cursor_name;
  LOOP
  FETCH cursor_name INTO var_oldCode;
  EXIT WHEN cursor_name%NOTFOUND;
  var_newCode:=var_newCode+1;
  update myTable set code = var_newCode where code = var_oldCode;
  END LOOP;
  CLOSE cursor_name;
 END procedure_name;

应该有效。 (抱歉现在无法测试。)