I am trying to find a way to split a text array into two arrays by their existence in a table.
Let's say that the users
table has these three IDs: 1, 2, 3
, and I have an input_array_ids
with values 1, 2, 5
. IDs 1, 2
exist in the table so it goes into another array called ids_valid
, and ID 5
goes into ids_invalid
. By the end, I want to run an update on valid IDs and notify the users which IDs have been updated and which IDs couldn't be found in the table.
CREATE FUNCTION update_status(p_id character varying DEFAULT NULL::character varying,
p_status character varying DEFAULT NULL::character varying) RETURNS character varying
LANGUAGE plpgsql
AS
$$
DECLARE
v_valid_ids users.id%type;
v_invalid_ids users.id%type;
v_result varchar(255);
v_ids text[];
BEGIN
v_ids = string_to_array(regexp_replace(p_id, '[\s+]', '', 'g'), ',');
--Do some magic to split v_ids into v_valid_ids and v_invalid_ids
UPDATE users
SET row_status = p_status,
updated_by = 'hxBiSP'
WHERE id = ANY (v_valid_ids);
v_result = 'Updated: ' || string_agg(v_valid_ids::character varying, ', ') || 'Could not update: ' || string_agg(v_invalid_ids::character varying, ', ');
RETURN v_result;
END ;
$$;
ALTER FUNCTION update_status(varchar, varchar) OWNER TO postgres;
How can I do it?