Split comma separated string using function in PostgreSQL
-- FUNCTION: public.splitstring(text, character)
-- DROP FUNCTION public.splitstring(text, character);
CREATE OR REPLACE FUNCTION public.splitstring(p_input Text, p_character Character)
RETURNS TABLE(item Text)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
BEGIN
DECLARE v_StartIndex integer := 1; v_EndIndex integer := 0;
BEGIN
IF (SUBSTRING(p_Input, length(p_Input) - 1, length(p_Input)) <> p_Character)
THEN
p_Input := concat(p_Input,'',p_Character);
END IF;
WHILE (POSITION(p_Character IN p_Input) > 0)
LOOP
v_EndIndex := POSITION(p_Character IN p_Input);
BEGIN
RETURN QUERY
SELECT SUBSTRING(p_Input, v_StartIndex, v_EndIndex - 1);
END;
p_Input := SUBSTRING(p_Input, v_EndIndex + 1, length(p_Input));
END LOOP;
END;
END;
$BODY$;
ALTER FUNCTION public.splitstring(Text, Character)
OWNER TO postgres;
Result:
SELECT public.splitstring('MSSql,MySql', ',')