Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loops with string in PostgreSQL

Here I am trying to concatenate a string with ,:

CREATE FUNCTION looping() RETURNS TABLE(round text)
DECLARE
  i RECORD;
BEGIN

FOR i IN select regexp_split_to_table('33,55,66,88', ',') as "asd"
LOOP
  str:= str || ',' ||(select  i."asd");
END LOOP;

END;
$$ LANGUAGE plpgsql; 

Is it true or am I missing something?

like image 888
Aijaz Chauhan Avatar asked May 31 '26 07:05

Aijaz Chauhan


1 Answers

Often, a set-based operation with standard SQL functions is superior to looping.
But if you need the control structure in plpgsql, would work like this (one of many ways):

CREATE FUNCTION f_loop2(OUT str text)
  RETURNS text AS
$func$
DECLARE
   i text;
BEGIN
str := '';

FOR i IN
   SELECT regexp_split_to_table('33,55,66,88', ',')
LOOP
  str :=  str || ',' || i;
END LOOP;

END
$func$ LANGUAGE plpgsql; 
like image 128
Erwin Brandstetter Avatar answered Jun 03 '26 01:06

Erwin Brandstetter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!