简体   繁体   中英

How do I loop through a list of columns in pg/PLSQL?

I have a table with about 3 dozen VARCHAR columns that all need the same cleanup before the record is inserted into the database (convert empty string to NULL). There are multiple apps accessing the DB, so I'd like to do this in a trigger. I could write code to check and set each column, but I'd like to loop through the columns instead. The function I wrote does not produce an error, but it also does not set empty columns to NULL.

CREATE OR REPLACE FUNCTION public.validate_flds() RETURNS trigger AS
$BODY$
DECLARE
  coldata VARCHAR;
  collist VARCHAR[];
BEGIN
  collist := ARRAY[NEW.fld01,NEW.fld02,NEW.fld03];
  FOREACH coldata IN ARRAY collist LOOP
    IF coldata = '' THEN coldata := NULL; END IF;
  END LOOP;
  RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;

What am I missing?

In

IF coldata = '' THEN coldata := NULL; END IF;

you alter the value of the variable while the NEW record remains unchanged. There is no easy way to do what you want in a loop. I would suggest using NULLIF().

begin
    new.fld01:= nullif(new.fld01, '');
    new.fld02:= nullif(new.fld02, '');
    new.fld03:= nullif(new.fld03, '');
    return new;
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