我正在尝试创建一个函数,该函数将有效地用作 UPSERT,并为成功的 UPDATE 返回 0 或为成功的 INSERT 返回新记录的 id。虽然该函数将成功创建,但当我尝试运行它时出现以下错误:
query has no destination for result data
我以这种方式运行它(数据显然被掩盖了):
select public.mergeaddress(0, 2, 'XXX XX XXXX', 'XXXX', 'XX', 'XXXXX', true, true, -XXX.XXXXXX, XX.XXXXXXX);
我知道我必须在这里遗漏一些明显的东西。有什么想法吗?
CREATE FUNCTION mergeAddress(integer, integer, varchar, varchar, varchar, varchar, boolean, boolean, float, float) RETURNS integer AS
$$
DECLARE new_id integer;
BEGIN
LOOP
UPDATE users_addresses SET users_id = $2, address_street = $3, address_city = $4, address_state = $5, address_zip = $6, is_private = $7, is_default = $8, long = $9, lat = $10 WHERE id = $1 RETURNING id;
IF found THEN
RETURN 0;
END IF;
BEGIN
INSERT INTO users_addresses VALUES (DEFAULT, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id INTO new_id;
RETURN new_id;
EXCEPTION WHEN unique_violation THEN
-- Restart the loop
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;