简体   繁体   中英

Filling null values with last not null one => huge number of columns

I want to copy rows from SOURCE_TABLE to TARGET_TABLE while filling null values with last not null one.

What I have :

SOURCE_TABLE :
       A |    B |    C | PARENT | SEQ_NUMBER
       1 |    2 | NULL |      1 |          1
    NULL | NULL |    1 |      1 |          2
    NULL |    3 |    2 |      1 |          3

DEST_TABLE is empty

What I want :

DEST_TABLE :
       A |    B |    C | PARENT | SEQ_NUMBER
       1 |    2 | NULL |      1 |          1
       1 |    2 |    1 |      1 |          2
       1 |    3 |    2 |      1 |          3

To achieve that I'm dynamically generating the following SQL :

insert into TARGET_TABLE (A, B, C)  
select  coalesce(A, lag(A ignore nulls) over (partition by parent order by seq_number)) as A,  
        coalesce(B, lag(B ignore nulls) over (partition by parent order by seq_number)) as B,  
        coalesce(C, lag(C ignore nulls) over (partition by parent order by seq_number)) as C,  
from SOURCE_TABLE; 

Everything works fine if SOURCE and TARGET tables have a small number of columns. In my case they have 400+ columns (yes this is bad but it is legacy and cannot be changed) and I got the following error :

ORA-01467: sort key too long

  • First I don't really understand this error. Is this because I'm using too many lag functions that use themselves "order by"/"partition by" ? Replace coalesce(A, lag(A....)) by coalesce(A,A) and the error disappear.
  • Then, is there a workaround or another way to achieve the same result ?

Thx

just do it using pl/sql anonymous block:

declare
   x tgt_table%rowtype; --keep values from last row
begin
   for r in (select * from src_table order by seq_number) loop
       x.a := nvl(r.a, x.a);
       ...
       x.z := nvl(r.z, x.z);
       insert into tgt_table
       values x;
   end loop;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM