Skip to content

Instantly share code, notes, and snippets.

@aaguilera
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaguilera/063902137bc7ee73eca4 to your computer and use it in GitHub Desktop.
Save aaguilera/063902137bc7ee73eca4 to your computer and use it in GitHub Desktop.
Convert string into a suitable CSV field as expected by MS Excel
--
-- Convert string into a suitable CSV field as expected by
-- Microsoft Excel.
-- See http://stackoverflow.com/a/21749399/1314986.
--
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment