2

I have a trigger in PostgreSQL

CREATE OR REPLACE FUNCTION table_update_func_pk1() RETURNS trigger AS $$
DECLARE
    ri RECORD;
    old_value TEXT;
    new_value TEXT;
BEGIN
    FOR ri IN
        SELECT column_name FROM information_schema.columns
        WHERE
            table_schema = quote_ident('public')
        AND table_name = quote_ident(TG_TABLE_NAME)
        ORDER BY ordinal_position
    LOOP
        EXECUTE 'SELECT ($1).' || ri.column_name || '::text' INTO new_value USING NEW;
        EXECUTE 'SELECT ($1).' || ri.column_name || '::text' INTO old_value USING OLD;

        IF new_value <> old_value AND ri.column_name != 'update_by' THEN
            INSERT INTO protokoll(datetime, operation, tabelle, field, pk1, old_value, new_value, update_by)
                   VALUES(now(), TG_OP, TG_TABLE_NAME, ri.column_name, NEW.cfg, old_value, new_value, NEW.update_by);
       END IF;
    END LOOP;
    RETURN NEW;
END;
$$  LANGUAGE plpgsql;

Sometimes if old_value is changed from NULL to normal value (or from normal value to NULL), the condition "new_value <> old_value" is NOT true but unknown. I would like ask, there is a method that I can get true in the case. Thanks.

1 Answer 1

4

Use is distinct from:

if new_value IS DISTINCT FROM old_value and ri.column_name <> 'update_by' then 
   ...
end if;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.