I am trying to write a function that takes an ID as an input and update some fields on that given ID. So far, it looks like this:
CREATE FUNCTION update_status(p_id character varying,
p_status character varying DEFAULT NULL::character varying) RETURNS character varying
LANGUAGE plpgsql
AS
$$
DECLARE
v_row_count bigint DEFAULT 0;
v_result varchar(255);
BEGIN
IF p_id IS NOT NULL THEN
SELECT count(user_id)
INTO v_row_count
FROM test
WHERE user_id = p_id;
END IF;
IF v_row_count <= 0 THEN
v_result = 'User not found';
RETURN v_result;
ELSE
IF p_id NOT LIKE '%,%' THEN
UPDATE test
SET status = p_status,
updated_by = 'admin'
WHERE user_id IN (p_id);
ELSE
--Here comes split and pass multiple IDs into an IN() operator
END IF;
END IF;
END
$$;
ALTER FUNCTION update_status(varchar, varchar) OWNER TO postgres;
Now, it is supposed to accept only one ID at a time but I wonder if I can get it to also accept multiple IDs -maybe even hundreds- once by splitting that single string into an array of IDs if it has a comma delimiter, then pass those to an IN()
operator. How can I get split a string into an array so I can feed it to an IN()
operator?