Plpgsql: How can i assign value to variable at declaration section?

≡放荡痞女 提交于 2019-12-02 09:20:58

Here is how you can do it:

create or replace function f1(my_number int default 1)

or

declare
my_number int :=1;

Look at declaration documentation

Assign value, general note

(about assign value to variable out of declaration section)

The language PLpgSQL syntax have many ways to say:

 Y := f(X);

The EXECUTE clause is only for "dynamic execution" (less performance),

 EXECUTE 'f(X)' INTO Y;     

Use Y := f(X); or SELECT for execute static declarations,

 SELECT f(X) INTO Y;

Use PERFORM statment when discard the results or to work with void returns:

 PERFORM f(X);     

There is more to it.

create or replace function f1(number int :=1) --This method is not working to me.

This works:

CREATE OR REPLACE FUNCTION f1(number int = 1) ...

Because := is the assignment operator of PL/pgSQL, while it's = for SQL. Details under this related question:

And CREATE FUNCTION is an SQL statement, even when creating a plpgsql function.

Inside plpgsql both variants are accepted, but only := is correct. = is tolerated, since it's such a widespread mistake people make. (Update: since pg 9.4, both variants are documented.) However, there are a few cases where the distinction is mandatory. For instance when calling the above function with named parameters. It has to be:

SELECT * FROM f1(number := 1);

Better yet, in Postgres 9.5 or later use => for parameter assignment in a function call:

SELECT * FROM f1(number => 1);

With:

SELECT * FROM f1(number = 1);

... Postgres would interpret number = 1 as an SQL expression and try to evaluate it, first looking for the identifier number in the outer scope of the calling statement. If it can't be found you get:

ERROR:  column "number" does not exist

That's the lucky case, and also the more common one. If number can be found in the scope of the calling statement and the evaluated boolean expression can be accepted as function parameter, you have successfully built an evil trap. Hard to debug if you were not aware of the distinction between := and = in the first place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!