简体   繁体   中英

how to get current row value in plpgsql function

I need to create plpgsql methods which use current row value without passing in parameter in update command.

I tried

create temp table test ( test text, result text ) on commit drop;
insert into test values ('1','');

CREATE OR REPLACE FUNCTION public.gettest() RETURNS text AS $$
DECLARE
  comp text := NULL;

BEGIN
EXECUTE 'SELECT ''Current row is '' ||test.test' INTO comp;
RETURN comp;
END; $$ LANGUAGE plpgsql STRICT STABLE;

update test set result = 'Result: ' || gettest();

but got exception

ERROR:  missing FROM-clause entry for table "test"
LINE 1: SELECT 'Current row is ' ||test.test
                                   ^
QUERY:  SELECT 'Current row is ' ||test.test
CONTEXT:  PL/pgSQL function gettest() line 6 at EXECUTE statement
********** Error **********

ERROR: missing FROM-clause entry for table "test"
SQL state: 42P01
Context: PL/pgSQL function gettest() line 6 at EXECUTE statement

How to fix ? How to fix without passing vaue to plpgsql method parameter ?

There is no such thing as an "implicit current row". You have to pass the the function whatever it needs as a parameter. You can however pass a complete row if you want to:

create temp table test (val text, result text ) on commit drop;
insert into test values ('1','');
insert into test values ('2','');

CREATE OR REPLACE FUNCTION gettest(p_test test) RETURNS text AS $$
DECLARE
  comp text := NULL;
BEGIN
   comp := 'Current row is '||p_test.val;
RETURN comp;
END; $$ LANGUAGE plpgsql STRICT STABLE;

update test set result = 'Result: ' || gettest(test);

I had to rename the column test to something else, otherwise the call gettest(test) would refer to the column not the whole table (=row) and thus it didn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM