Ang Chin Han wrote:
Tom Lane wrote:

create function greatest(anyelement, anyelement) returns anyelement as
'select case when $1>$2 then $1 else $2 end' language sql;

Any chance of this making it into 7.4's contrib? Maybe with enough documentation to make it a tutorial for PostgreSQL's user functions?
>
>> You do have to create several greatest() functions for different
>> numbers of arguments, but not one for each datatype you want to
>> handle.
>
> Insignificant, compared with the flexiblity.


I don't think it's worth putting in contrib, but for the archives:


create or replace function make_greatest() returns text as '
declare
v_args int := 32;
v_first text := ''create or replace function greatest(anyelement, anyelement) returns anyelement as ''''select case when $1 > $2 then $1 else $2 end'''' language ''''sql'''''';
v_part1 text := ''create or replace function greatest(anyelement'';
v_part2 text := '') returns anyelement as ''''select greatest($1, greatest($2'';
v_part3 text := ''))'''' language ''''sql'''''';
v_sql text;
begin
execute v_first;
for i in 3 .. v_args loop
v_sql := v_part1;
for j in 2 .. i loop
v_sql := v_sql || '',anyelement'';
end loop;


v_sql := v_sql || v_part2;

    for j in 3 .. i loop
      v_sql := v_sql || '',$'' || j::text;
    end loop;

v_sql := v_sql || v_part3;

    execute v_sql;
  end loop;
  return ''OK'';
end;
' language 'plpgsql';

select make_greatest();

Now you should have 31 "greatest" functions, accepting from 2 to 32 arguments. *Not* heavily tested, but seemed to work for me.

regression=# select greatest(112,2,3,4,5,6,7,8,9,10,1234,2,3,4,5,66,7,8,9,10,1,27,3,4,5,6,347,8,9,10,1,2);
greatest
----------
1234
(1 row)



I'll leave "least()" as an exercise for the reader ;-)


HTH,

Joe



---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Reply via email to