PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Divisione di stringhe separate da virgole nella funzione PL/pgSQL

Blue Star ha già menzionato che esiste una funzione incorporata per convertire una stringa separata da virgole in un array.

Ma suggerirei di non passare una stringa separata da virgole per cominciare. Se vuoi passare un numero variabile di ID usa un variadic parametro.

Inoltre non è necessario eseguire prima un SELECT, puoi chiedere al sistema quante righe sono state aggiornate dopo l'istruzione UPDATE.

CREATE FUNCTION update_status(p_status text, p_id variadic integer[]) 
  RETURNS character varying
  LANGUAGE plpgsql
AS
$$
DECLARE
  v_row_count bigint DEFAULT 0;
BEGIN
  UPDATE test
  SET status     = p_status,
      updated_by = 'admin'
  WHERE user_id = any (p_id);
    
  get diagnostics v_row_count = row_count;
  if v_row_count = 0 then 
    return 'User not found';
  end if;
  
  return concat(v_row_count, ' users updated');
END
$$;

Puoi usarlo in questo modo:

select update_status('active', 1);
select update_status('active', 5, 8, 42);

Se per qualche motivo "devi" passare questo come un singolo argomento, usa invece un array reale:

CREATE FUNCTION update_status(p_status text, p_id integer[]) 

Quindi passalo in questo modo:

select update_status('active', array[5,8,42]);

o

select update_status('active', '{5,8,42}');