[GENERAL] Find difference between two Text fields

2009-07-24 Thread Peter Hunsberger
Can anyone give me a way to find the difference between two text
fields on a character by character basis.  Essentially,  I'd like to
logically AND the two together and for any position that has a
non-zero result show whatever character is in that position for the
second string.  The solution can be postgres specific but something
approaching ANSI SQL would also be helpful (if possible).

-- 
Peter Hunsberger

-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general


Re: [GENERAL] Find difference between two Text fields

2009-07-24 Thread Aleksander Kmetec

Hi,

there might be a better solution out there, but it seemed like an interesting 
problem so I wrote this function:

CREATE OR REPLACE FUNCTION stringdiff(text, text)
RETURNS TEXT
AS $$
SELECT array_to_string(ARRAY(
SELECT
CASE WHEN substring($1 FROM n FOR 1) = substring($2 FROM n FOR 1)
 THEN ' '
 ELSE substring($2 FROM n FOR 1)
END
FROM generate_series(1, character_length($1)) as n), '');
$$ language sql;


Use it like this:
SELECT stringdiff('aa', 'axaaacaaza');

 stringdiff

  x   c  z

Regards,
Aleksander


Peter Hunsberger wrote:

Can anyone give me a way to find the difference between two text
fields on a character by character basis.  Essentially,  I'd like to
logically AND the two together and for any position that has a
non-zero result show whatever character is in that position for the
second string.  The solution can be postgres specific but something
approaching ANSI SQL would also be helpful (if possible).



--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general