FUNCTION next_term (pstrLine IN OUT VARCHAR2,
pstrSeperator IN VARCHAR2 := ',') RETURN VARCHAR2 IS
lnumPos NUMBER;
lstrLine VARCHAR2(32767);
lstrTerm VARCHAR2(32767);
lstrQuote VARCHAR2(1) := NULL;
BEGIN
-- Make a copy of the line, removing any leading whitespace
lstrLine := LTRIM(pstrLine);
-- Check for quoted strings
lstrQuote := SUBSTR(lstrLine,1,1);
IF lstrQuote IN ('''','"') THEN
-- Term is a quoted string, remove the starting quote
lstrLine := SUBSTR(lstrLine,2);
LOOP
-- ... look for the closing quote
lnumPos := INSTR(lstrLine,lstrQuote);
IF lnumPos > 0 THEN
-- We've found one, but need to check to see if it's
-- a '' or ""...
IF SUBSTR(lstrLine,lnumPos+1,1) = lstrQuote THEN
-- ... yes it is, add a single quote character to the
-- term and keep looking...
lstrTerm := lstrTerm||SUBSTR(lstrLine,1,lnumPos);
lstrLine := SUBSTR(lstrLine,lnumPos+2);
ELSE
-- It's a proper closing quote. Add the rest of the
-- string to the term
lstrTerm := lstrTerm||SUBSTR(lstrLine,1,lnumPos-1);
lstrLine := SUBSTR(lstrLine,lnumPos+1);
-- Now look for the comma
lnumPos := INSTR(lstrLine,pstrSeperator);
IF lnumPos > 0 THEN
lstrLine := SUBSTR(lstrLine,lnumPos+LENGTH(pstrSeperator));
ELSE
-- No comma found, ignore the rest of the line
lstrLine := NULL;
END IF;
EXIT;
END IF;
ELSE
-- String has an opening quote but not a closing one
RAISE VALUE_ERROR;
END IF;
END LOOP;
ELSE
-- not a quoted string - life's a lot easier!
-- Find the next comma
lnumPos := INSTR(lstrLine,pstrSeperator);
IF lnumPos > 0 THEN
-- Found one: Before the comma is the term, after it the
-- rest of the line
lstrTerm := SUBSTR(lstrLine,1,lnumPos-1);
lstrLine := SUBSTR(lstrLine,lnumPos+LENGTH(pstrSeperator));
ELSE
-- No comma, so this is the last term.
lstrTerm := lstrLine;
lstrLine := NULL;
END IF;
END IF;
pstrLine := lstrLine;
RETURN RTRIM(lstrTerm);
END;