St.*_*rio 1 sql postgresql plpgsql
我试着编写简单的函数:
CREATE OR REPLACE FUNCTION add_mail_settings_column() RETURNS void AS $$
BEGIN
asd text := 'asd';
END $$
LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)
但它不起作用:
ERROR: syntax error at or near "asd"
LINE 3: asd text := 'asd';
Run Code Online (Sandbox Code Playgroud)
但如果我按如下方式移动它:
CREATE OR REPLACE FUNCTION add_mail_settings_column() RETURNS void AS $$
DECLARE
asd text := 'asd';
BEGIN
END $$
LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)
它工作正常.那么我们不能把变量声明放到函数体中吗?
Mik*_*ll' 10
您只能在块的DECLARE部分中声明变量.但是你可以在块内编码块.这是直接从PostgreSQL文档中复制PL/pgSQL的结构.
CREATE FUNCTION somefunc() RETURNS integer AS $$
<< outerblock >>
DECLARE
quantity integer := 30;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
quantity := 50;
--
-- Create a subblock
--
DECLARE
quantity integer := 80;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50
END;
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50
RETURN quantity;
END;
$$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)