0

我有一个名为 sales_staff_08 的表,名字、姓氏、用户名是 3 个列。

用户名使用名字和姓氏连接。

因为它可能会被复制。因此,我想通过添加一些数字来避免。

当前表

USERNAME   
---------- 
JOHSMITH1 
TOMNGUYE1
STEREDMO1
BOBJOHN1
CARJONES1
DANCREIG1
STEREDMO1
TOMNGUYE1

我想更新重复的 RECORD,它应该显示如下:

USERNAME   
---------- 
JOHSMITH1
TOMNGUYE1
STEREDMO1
BOBJOHN1
CARJONES1
DANCREIG1
STEREDMO2
TOMNGUYE2

我第一次尝试更新记录

 CREATE OR REPLACE PROCEDURE proc_concate_names IS 

 vc_username VARCHAR(25);
 v_number NUMBER (2) := 1;

 CURSOR cur_concate_username IS 
 SELECT firstname, surname, username FROM sales_staff_08; 

 BEGIN

    FOR rec_cur_concate IN cur_concate_username 

    LOOP

    vc_username := rec_cur_concate.firstname || rec_cur_concate.surname || v_number;

    UPDATE sales_staff_08 ss
    SET username = vc_username
    WHERE ss.username = rec_cur_concate.username;

 END LOOP; 

 END proc_concate_names;
 /
4

2 回答 2

2

你可以用一个命令来做到这一点:

merge into sales_staff_08 d
using (select firstname ||surname || row_number() 
           over (partition by username order by firstname) un, rowid 
       from sales_staff_08 ) s
on (d.rowid = s.rowid)
when matched then update set d.username = s.un;

这是一个 sqlfiddle 演示

正如@Plouf 所说,这也可以作为更新命令来完成:

update sales_staff_08 d
set d.username = (
  select un from (
    select firstname ||surname || row_number() 
            over (partition by firstname, surname order by firstname) un 
     from sales_staff_08
  ) s
  where s.rowid = d.rowid
)

这是另一个 sqlfiddle

于 2013-02-11T06:53:52.363 回答
2

A.B.Cade answer is more reliable. First, merge and update will work faster if there are millions of rows. Because in first case, you are using both plsql engine and sql engine for operation. It means in each loop of plsql engine, it will call sql engine. In second case it will use full independent sql engine which is faster.

于 2013-02-11T09:47:42.647 回答