Pages

Monday, May 9, 2011

SQL -=- Records to CSV SQL function

Hi!

If you want to convert an SQL resultset to a CSV string, your can use the following function.
  
Function

CREATE OR REPLACE FUNCTION myschema.to_csv(query_to_convert character varying, separator character varying)
  RETURNS text AS
$BODY$
declare
    r RECORD;
    t character varying;
begin
    t := '';
    
    FOR r IN EXECUTE query_to_convert LOOP
        t := t || r.data || separator;
    END LOOP;

    -- We removes the trailing comma
    RETURN substring(t, 0, char_length(t)-1) ;
end;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE
  COST 100;

Function Call


SELECT myschema.to_csv('SELECT mycol as data  FROM myschema.mytable;',','); 

This will return a varchar containing all the records reparated with the specified delimiter, in our example a comma.

No comments:

Post a Comment