Consider the following PL/pgSQL procedure:
DO
$$
DECLARE
_notes VARCHAR := 'something';
_id BIGINT := 11683;
BEGIN
update person set notes = CASE WHEN LENGTH(_notes) = 0 THEN notes ELSE _notes END WHERE id = _id;
END
$$
The goal is to update notes column only when _notes variable is not an empty string. This example works, but _notes variable is used twice in UPDATE statement. I would like to know if there is a way to do it using it only once (without writing a custom database function).
The reason I need this? I am writing a Java class which automatically writes POJOs to the database. Some fields can be marked to be saved only when non-empty. As JDBC supports only positional parameters, with existing solution I would need to specify the same parameter twice, which would not be consistent with the rest of my code.
A side question: if the value is empty, update statement would essentially read: UPDATE person SET notes = notes
. Is PostgreSQL smart enough not to do any actual updating in this case?
EDIT
Apparently, this is not possible. The only way would be to write a custom PL/pgSQL function, something along the lines of:
CREATE OR REPLACE FUNCTION coalesce_empty(varchar, varchar) RETURNS varchar AS $$
SELECT CASE WHEN LENGTH($1) = 0 THEN $2 ELSE $1 END;
$$ LANGUAGE sql IMMUTABLE;
But that requires full control over the database.