Search This Blog

column values to comma separated string using CURSOR

For example we need to display the locations in one string separated with commas:




we need to display the values like "New York, Dalas, Chicago, Boston"

  Function col_values_to_comma_string ( )
    return char
    is
      cursor string_cur is
        select loc
        FROM dept;

      l_length number := NULL;
      l_val varchar2(50) := NULL;
      l_dup_lines number := NULL;
  begin

        for rec_string in string_cur loop
                    l_val := rec_string.loc||','||l_val;
        end loop;
       
        l_length := length(l_val);
        l_val := substr(l_val,1,l_length-1);

        return l_val;
end;

Call the function

declare
    v_loc varchar2(100);

begin

v_loc := col_values_to_comma_string;

dbmsoutput.put_line('Locations = '||v_loc);

end;

New York, Dalas, Chicago, Boston