| From: | Joe Conway <mail(at)joeconway(dot)com> | 
|---|---|
| To: | Chris Travers <chris(at)travelamericas(dot)com> | 
| Cc: | pgsql-sql(at)postgresql(dot)org | 
| Subject: | Re: How to retrieve N lines of a text field. | 
| Date: | 2004-01-29 17:52:46 | 
| Message-ID: | 4019486E.7000807@joeconway.com | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-sql | 
Chris Travers wrote:
> This is a complex issue, and i am tryign to figure out how to use regular
> expressions to resolve this issue.  I need to retrieve the first N lines of
> a text field.  N would be assigned using a parameterized query, if possible.
How 'bout something like this:
CREATE OR REPLACE FUNCTION first_n_lines(text, int)
RETURNS setof text AS '
DECLARE
   i int := 0;
   oneline text;
BEGIN
   LOOP
     i := i + 1;
     IF i > $2 THEN
       EXIT;
     END IF;
     SELECT INTO oneline split_part($1, ''\n'', i);
     IF oneline = '''' THEN
       EXIT;
     END IF;
     RETURN NEXT oneline;
   END LOOP;
   RETURN;
END
' LANGUAGE 'plpgsql';
regression=# select * from first_n_lines('abc\ndef\nghi', 2);
  first_n_lines
---------------
  abc
  def
(2 rows)
HTH,
Joe
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Stephan Szabo | 2004-01-29 18:27:57 | Re: query not using index for descending records? | 
| Previous Message | Tom Lane | 2004-01-29 17:24:14 | Re: query not using index for descending records? |