使用循环进行PL / SQL更新

时间:2018-01-30 23:48:46

标签: oracle plsql

我必须更新50名员工的身份证号码。身份证号码依次为

100001, 100002, 100003 ... 100050

我需要使用其他序列系列更新它们,例如

1004001, 1004002, 1004003 ... 1004050

所以,我想使用循环更新。但我不明白该怎么做。我正在使用PL / SQL Developer和Oracle。

然而,我所尝试的是:

DECLARE 
  i number(1); 
  j number(1); 
BEGIN 
  << outer_loop >> 
  FOR i IN 100001..100051 LOOP             

    << inner_loop >>      
    FOR j IN 1..3 LOOP 
      update employees e
      set    e.IDENTIFICATION_NUMBER = j
      where  e.IDENTIFICATION_NUMBER = i;
    END loop inner_loop;          

  END loop outer_loop; 
END; 
/

2 个答案:

答案 0 :(得分:3)

您是否尝试使用j

更新i的值
 DECLARE 
      i number(1); 
      j number(1); 
    BEGIN 
      j:= 1004001;
      << outer_loop >> 
      FOR i IN 100001..100051 LOOP             

          update employees e
          set    e.IDENTIFICATION_NUMBER = j
          where  e.IDENTIFICATION_NUMBER = i;
          j:=j+1;       

      END loop outer_loop; 
    END; 
    /

答案 1 :(得分:2)

您要将员工ID号的前3个字符(例如100来自 100 001)替换为1004,然后您可以通过运行更新语句来完成,

UPDATE employees
   SET identification_number = '1004'||SUBSTR(identification_number,4)
 WHERE identification_number BETWEEN 100001 AND 100050;

如果你想使用LOOP

BEGIN
    FOR emp_l IN (SELECT identification_number
                    FROM employees
                   WHERE identification_number BETWEEN 100001 AND 100050)
    LOOP
        UPDATE employees
           SET identification_number = '1004'||SUBSTR(emp_l.identification_number,4)
         WHERE identification_number = emp_l.identification_number;
    END LOOP;
END;
/

OR

BEGIN
    FOR emp_id IN 100001..100050
    LOOP
        UPDATE employees
           SET identification_number = '1004'||SUBSTR(emp_id,4)
         WHERE identification_number = emp_id;
    END LOOP;
END;
/