Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't declare variable inside function on PostgreSQL

Tags:

postgresql

I am writing function in PostgreSQL but it doesn't allow me to declare variable inside it. Here is the function.

CREATE FUNCTION clean_emp() RETURNS void AS 
$func$
DECLARE cnt varchar;

$func$ LANGUAGE SQL;

Error Message ERROR: syntax error at or near "varchar" SQL state: 42601 Character: 66

like image 229
AAjit Avatar asked Feb 08 '23 10:02

AAjit


1 Answers

It is not surprise. The language SQL doesn't support variables. You have to use the language plpgsql.

CREATE OR REPLACE FUNCTION clean_emp()
RETURNS void AS $$
DECLARE cnt varchar;
BEGIN
END;
$$ LANGUAGE plpgsql;

See more in documentation http://www.postgresql.org/docs/current/static/plpgsql.html.

PostgreSQL has more languages for writing function. The SQL language is perfect for one line single statement macros. The PLpgSQL is classical native language similar to Oracle's PL/SQL with embedded SQL.

like image 167
Pavel Stehule Avatar answered Feb 12 '23 22:02

Pavel Stehule