如何更新 Oracle 中同一 table 中的多行?

How to update multiple rows within the same table in Oracle?

我正在使用 Oracle DB Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production

我有以下创建 table 脚本。 我想用相同的值

更新同一 table 中的多行

例如

CREATE TABLE dummy_test_table(seq_no) AS
SELECT '0000000957' FROM dual UNION ALL
SELECT '0000000957' FROM dual UNION ALL
SELECT '0000000958' FROM dual UNION ALL
SELECT '0000000958' FROM dual UNION ALL
SELECT '0000000969' FROM dual UNION ALL
SELECT '0000000969' FROM dual UNION ALL
SELECT '0000000957' FROM dual UNION ALL
SELECT '0000000958' FROM dual UNION ALL
SELECT '0000000959' FROM dual;

我想通过 sql 或 plsql 更新 table 并使用具有相似 batch_id 的相同序列号设置批次 ID 并获取 o/p 如下。有人可以帮助到达查询。

Seq_no Batch_Id
0000000957 001
0000000957 001
0000000957 001
0000000958 002
0000000958 002
0000000958 002
0000000969 003
0000000969 003
0000000970 004

谢谢

row_number 分析函数的帮助下:

SQL> ALTER TABLE dummy_test_table ADD batch_id VARCHAR2 (10);

Table altered.

SQL> UPDATE dummy_test_table a
  2     SET a.batch_id =
  3            (WITH
  4                temp
  5                AS
  6                   (SELECT seq_no,
  7                           ROW_NUMBER () OVER (ORDER BY seq_no) batch_id
  8                      FROM (SELECT DISTINCT seq_no
  9                              FROM dummy_test_table))
 10             SELECT LPAD (t.batch_id, 3, '0')
 11               FROM temp t
 12              WHERE t.seq_no = a.seq_no);

9 rows updated.

结果:

SQL>   SELECT *
  2      FROM dummy_test_table
  3  ORDER BY seq_no, batch_id;

SEQ_NO     BATCH_ID
---------- ----------
0000000957 001
0000000957 001
0000000957 001
0000000958 002
0000000958 002
0000000958 002
0000000959 003
0000000969 004
0000000969 004

9 rows selected.

SQL>

一种选择是在 MERGE DML 语句中使用 DENSE_RANK() 分析函数,例如

MERGE INTO dummy_test_table d1
USING (SELECT seq_no, LPAD(DENSE_RANK() OVER(ORDER BY seq_no), 3, '0') AS dr
         FROM dummy_test_table) d2
   ON (d1.rowid = d2.rowid)
 WHEN MATCHED THEN UPDATE SET d1.batch_id = dr

Demo

在我看来,无需添加额外的列并填充它。相反,您可以使用这样的查询或创建一个 SQL-view( 并在需要时查询 ) :

--CREATE OR REPLACE v_dts AS
SELECT seq_no, LPAD(DENSE_RANK() OVER(ORDER BY seq_no), 3, '0') AS batch_id
  FROM dummy_test_table