oracle - 按组分配序列到分区

时间:2015-03-30 15:29:21

标签: oracle partition

select row_number() over(partition by col1,col2), col1, col2, col3 
from table1 
where xxxx...

使用上面的查询时,如何为每个组分配sequence.nextval?

1 个答案:

答案 0 :(得分:1)

我发现了一种只使用SQL的方法。关键是为每个分区条件只返回一行,并获得每个值的序列值。

MERGE INTO table1
USING      (SELECT col1, col2, your_sequence.NEXTVAL AS seq
            FROM   (SELECT DISTINCT col1, col2 FROM table1)) s
ON         (table1.col1 = s.col1 AND table1.col2 = s.col2)
WHEN MATCHED THEN
   UPDATE SET seq_column = s.seq
      WHERE      some_column = some_condition

使用PL / SQL,您可以循环查询结果并更新每个分区:

DECLARE
   CURSOR cur_partitions IS
      SELECT DISTINCT col1, col2
      FROM   table1
      WHERE  some_column = some_condition;

   v_seq NUMBER;
BEGIN
   FOR r_partition IN cur_partition LOOP
      v_seq := your_sequence.NEXTVAL;

      UPDATE table1
      SET    seq_column = v_seq
      WHERE      col1 = r_partition.col1
             AND col2 = r_partition.col2
             AND some_column = some_condition;
   END LOOP;
END;