Frank's comment is what led me the right way - plpgsql, the format() function, and the EXECUTE command worked perfectly.