1
CREATE OR REPLACE FUNCTION "public"."sxfun"("jcbh" text)
  RETURNS "pg_catalog"."int4" AS $BODY$
declare leftplayer TEXT;
declare rightplayer TEXT;
declare leftcoin int;
    BEGIN
    SELECT player1 into leftplayer,player2 into rightplayer FROM table1 WHERE id=$1;
    SELECT SUM(playcoin) into leftcoin FROM table2 WHERE playname=leftplayer 
    COMMIT;
END$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

this code syntax error,let how to solve it,please

2
  • What exactly is it you want to return? The sum() value? Commented Oct 31, 2020 at 9:50
  • yes.i do,dou you how to solve it? Commented Oct 31, 2020 at 10:13

1 Answer 1

1

You are missing a return statement. In PL/pgSQL, declare starts a block, there is no need to repeat the keyword for every variable. And you can't commit in a function - and you don't need it to begin with.

As documented in the manual you need to use return to return a value from a function.

To store multiple columns into multiple variables, you need to separate them with a comma, not repeat the INTO clause.

Note that sum() returns a bigint, so your variable and return type should also be defined as bigint.

CREATE OR REPLACE FUNCTION public.sxfun(jcbh text)
  RETURNS bigint
AS 
$BODY$
declare 
  leftplayer TEXT;
  rightplayer TEXT;
  leftcoin bigint;
BEGIN
   SELECT player1, player2  
    into leftplayer, rightplayer 
  FROM table1 
  WHERE id = jcbh;    
  SELECT SUM(playcoin) 
     into leftcoin 
  FROM table2 
  WHERE playname = leftplayer;

  return leftcoin; --<< return the value
END
$BODY$
LANGUAGE plpgsql;

If id is a number (which the name usually indicates), the parameter jcbh should be declared as integer, not as text.


Note that you can simplify this to a single statement. There is no need for intermediate variables:

CREATE OR REPLACE FUNCTION public.sxfun(jcbh text)
  RETURNS bigint 
AS 
$BODY$
  SELECT SUM(playcoin) 
  FROM table2 
  WHERE playname IN (select leftplayer
                     FROM table1 
                     WHERE id = jcbh); 
$BODY$
LANGUAGE sql;
Sign up to request clarification or add additional context in comments.

2 Comments

how to use leftplayer or how get leftplayer value?
I've revised the question. Please take a look at it for me。

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.