Fill null field with first non-null first field

0

Good afternoon,

I wanted to populate the null fields with the first non-null first field in an entire table. Do you know if you can?

How is the table:

Howshouldthetablelooklike:

    
asked by anonymous 18.04.2017 / 21:12

1 answer

0

As your table will always maintain this string, a function can be made that first stores the code and when this field is null it uses the previously saved variable.

Follow the example below:

do $$
declare
  vRegistros record;
  vCodigo integer;
begin
  --Executa a query e a cada iteração grava a tupla em vRegistros
  for vRegistros in select * from codigo_null order by id loop
    -- Se o campo codigo não for nulo a variável vCodigo receberá o seu valor
    if vRegistros.codigo is not null then
      vCodigo := vRegistros.codigo;
    else
    -- Quando o código for nulo irá atualizar o registro correspondente com o código gravado na iteração anterior
      update codigo_null
      set codigo=vCodigo
      where id=vRegistros.id;
    end if;
  end loop;
end
$$ language plpgsql;
    
20.04.2017 / 23:55