How would you write a function in postgresql with execute and if exists statements?
CREATE FUNCTION replace_value(var_id char, var_data text, table_name char) RETURNS void AS $$
BEGIN
IF EXISTS EXECUTE'(SELECT id FROM ' ||table_name|| ' WHERE id = '||var_id||')'
THEN EXECUTE 'UPDATE ' ||table_name||'
SET (id, data) = '||(var_id, var_data)||';'
ELSE EXECUTE 'INSERT INTO ' ||table_name||' (id, data)
VALUES '||(var_id, var_data)||';'
END IF;
RETURN;
END;
$$ LANGUAGE plpgsql;
I would also use table_name as an argument passed to the function and some variables in this example 'var_id' and 'var_data'. I know that using table name in postgresql function is only possible when using the execute statement.