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

帅比萌擦擦* 提交于 2019-12-20 06:30:04

问题


For example.

--Assigning value to variable in function as a parameter.
create or replace function f1(number int :=1) --This method is not working to me. 

or

--Assigning values to variables at declaration section.
declare
       number int :=1; -- Here i need to assign the value to number but its not working.
       name varchar :='xyz'; 

回答1:


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




回答2:


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);     



回答3:


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:

  • The forgotten assignment operator "=" and the commonplace ":="

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.



来源:https://stackoverflow.com/questions/21932493/plpgsql-how-can-i-assign-value-to-variable-at-declaration-section

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