Skip to content

Instantly share code, notes, and snippets.

@fritzy
Created May 11, 2015 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fritzy/9d03ec8d1cea7e7280de to your computer and use it in GitHub Desktop.
Save fritzy/9d03ec8d1cea7e7280de to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION generate_update_query(value JSON, tbl TEXT) RETURNS TEXT as $$
DECLARE
key TEXT;
sets TEXT[];
BEGIN
FOR key IN
SELECT json_object_keys(value)
LOOP
IF (key != 'id') THEN
SELECT array_append(sets, format('%I=%L', key, value->>key)) INTO sets;
END IF;
END LOOP;
RETURN format('UPDATE %I SET ', tbl) || array_to_string(sets, ', ') || format(' WHERE id=%L', (value->>'id')::integer);
END;
$$ language 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment