我试图在PostgreSQL SQL脚本中声明具有默认值0的整数变量:
DECLARE user_id integer;
但它返回异常:
错误:"整数"或附近的语法错误
我不确定如何声明变量,然后在循环时使用此变量。
您必须将代码放入用户定义的函数中。它将在SQL窗口上不起作用。下面的示例是返回您发送的号码的函数。变量
--mybase is your database name. If public, remove it.
CREATE OR REPLACE FUNCTION mybase.my_new_rotine(numeric)
RETURNS numeric AS
$BODY$
--here, get the first variable from function
declare id numeric= $1;
begin
--return the number
return id;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
然后,您可以在SQL窗口上使用它:
select * from mybase.my_new_rotine(1)
将返回1
您无法在SQL语句中使用声明。您要做的需要PLPGSQL。Danielarend的答案是正确的,但是您可能需要探索DO(https://www.postgresql.org/docs/current/current/static/sql-do.html),可以让您编写adhoc plpgsql,而无需定义函数。/p>