PostgreSQL自定义函数报错‘syntax error at return’,请求排查问题原因
Ah, I see the issue here! The problem comes from a mismatch between the language you specified and the procedural syntax you used in your function body. Let me break this down and fix it for you.
Why the "syntax error at return" happens
You declared your function with language sql, but SQL-language functions don't support procedural constructs like begin/end blocks or explicit return statements. SQL functions are designed to be simple expression-based routines that directly return a computed result.
Fix 1: Keep it as a lightweight SQL function
If you just need to compute the sum of three integers, you can rewrite the function to use pure SQL syntax (no procedural blocks):
create function total (number1 integer, number2 integer, number3 integer) returns integer as $$ select number1 + number2 + number3; $$ language sql;
Fix 2: Switch to PL/pgSQL for procedural logic
If you plan to add more complex logic later (like conditional checks, loops, or multiple statements), switch to the PL/pgSQL language, which supports begin/end blocks and return statements:
create function total (number1 integer, number2 integer, number3 integer) returns integer as $$ begin return number1 + number2 + number3; end; $$ language plpgsql;
Both fixes will resolve the syntax error and give you the sum you're looking for. The SQL version is more lightweight for simple calculations, while PL/pgSQL gives you flexibility for more advanced use cases.
内容的提问来源于stack exchange,提问作者D. Gillard

