Sql function without select / insert / delete / update

I am not so experienced with sql, and this is my (maybe stupid) question:

I have the following request

select *
from myTable
where lower(replace(lastname, 'ü', 'ue')) = lower(replace(someStr, 'ü', 'ue'))

Is it possible to replace

lower(replace(lastname, 'ü', 'ue')) = lower(replace(someStr, 'ü','ue'))

with function?

Something like that:

select *
from idmanlight.nethz_user
where myFunction(lastname) = myFunction(someStr)

I tried to define the function as follows:

CREATE FUNCTION myFunction(IN str character varying) RETURNS void AS $$
LOWER(replace(replace(replace((str, 'ü', 'ue'), 'ä', 'ae'), 'ö', 'oe'));
$$ LANGUAGE sql;

but running it, I get an error

ERROR: Syntax error by "LOWER" SQL state: 42601 Character: 88

All the examples I found always contain selection, deletion, updating, and insertion into the body of the function.

Actually it is possible to define a function that has no choice, deletion, update, insertion into it?

I am using PostgresSql 9.2.

+4
source share
2 answers

sql :

CREATE FUNCTION myFunction(str text) RETURNS text AS $$
  SELECT LOWER(replace(replace(replace((str, 'ü', 'ue'), 'ä', 'ae'), 'ö', 'oe'));
$$ IMMUTABLE STRICT LANGUAGE sql;

, :

CREATE OR REPLACE FUNCTION translit(text)
    RETURNS text
AS $$
DECLARE
    _str    text := $1;
    _find   constant text :=    'ÀÁÂÃÄÅĀĄĂÆÈÉÊËĒĘĚĔĖÐÌÍÎÏĪĨĬĮİIJÒÓÔÕÖØŌŐŎŒÙÚÛÜŪŮŰŬŨŲÝŶŸ' ||
                                'àáâãäåāąăæèéêëēęěĕėðìíîïīĩĭįıijòóôõöøōőŏœùúûüūůűŭũųýÿŷ' ||
                                'ÇĆČĈĊĎĐƑĜĞĠĢĤĦĴĶŁĽĹĻĿÑŃŇŅŊŔŘŖŚŠŞŜȘſŤŢŦȚÞŴŹŽŻ' ||
                                'çćčĉċďđƒĝğġģĥħĵĸķłľĺļŀñńňņʼnŋŕřŗśšşŝșßťţŧțþŵžżź';
    _repl   constant text :=    'AAAAAAAAAAEEEEEEEEEEIIIIIIIIIIOOOOOOOOOOUUUUUUUUUUYYY' ||
                                'aaaaaaaaaaeeeeeeeeeeiiiiiiiiiioooooooooouuuuuuuuuuyyy' ||
                                'CCCCCDDFGGGGHHJKLLLLLNNNNNRRRSSSSSSTTTTTWZZZ' ||
                                'cccccddfgggghhjkklllllnnnnnnrrrsssssstttttwzzz';
BEGIN
    -- Bail if the string is empty.
    IF  _str = ''
    THEN
        RETURN _str;
    END IF;

    -- Common expansions.
    _str := replace(_str, 'ſ', 'SS');
    _str := replace(_str, 'ß', 'ss');
    _str := replace(_str, 'Å', 'AA');
    _str := replace(_str, 'å', 'aa');
    _str := replace(_str, 'IJ', 'IJ');
    _str := replace(_str, 'ij', 'ij');
    _str := regexp_replace(_str, '([ÄÆÖŒÜ])', E'\\1E', 'g');
    _str := regexp_replace(_str, '([äæöœü])', E'\\1e', 'g');

    -- Translate what left.
    _str := translate(_str, _find, _repl);

    RETURN _str;
END;
$$ IMMUTABLE STRICT LANGUAGE plpgsql COST 1;
+3

. . :

RETURN LOWER(...)

RETURN SELECT LOWER(...)
+2

All Articles