pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Joe Conway <mail@joeconway.com>
To: Chris Travers <chris@travelamericas.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: How to retrieve N lines of a text field.
Date: Thu, 29 Jan 2004 09:52:46 -0800
Message-ID: <4019486E.7000807@joeconway.com> (raw)
In-Reply-To: <010301c3e679$077698b0$5444053d@winxp>
References: <010301c3e679$077698b0$5444053d@winxp>

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




view thread (3+ messages)

Message-ID: <4019486E.7000807@joeconway.com>
Permalink:  ../4019486E.7000807@joeconway.com/
Also on:    postgresql.org/message-id/4019486E.7000807@joeconway.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: mail@joeconway.com, chris@travelamericas.com
  Subject: Re: How to retrieve N lines of a text field.
  In-Reply-To: <4019486E.7000807@joeconway.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox