这样的事情:
CREATE OR REPLACE FUNCTION get(param_id integer)
RETURNS integer AS
$BODY$
BEGIN
SELECT col1 FROM TABLE WHERE id = param_id;
END;
$BODY$
LANGUAGE plpgsql;
我想避免使用DECLARE
。
答案 0 :(得分:65)
是的,你可以。有很多方法。
RETURN (SELECT ...)
CREATE OR REPLACE FUNCTION get(_param_id integer)
RETURNS integer AS
$func$
BEGIN
RETURN (SELECT col1 FROM TABLE WHERE id = _param_id);
END
$func$ LANGUAGE plpgsql;
OUT
或INOUT
参数CREATE OR REPLACE FUNCTION get(_param_id integer, OUT _col1 integer)
-- RETURNS integer -- "RETURNS integer" is optional noise in this case
AS
$func$
BEGIN
SELECT INTO _col1 col1 FROM TABLE WHERE id = _param_id;
-- also valid, but discouraged:
-- _col1 := col1 FROM TABLE WHERE id = _param_id;
END
$func$ LANGUAGE plpgsql;
IN
参数自 Postgres 9.0 以来,您还可以使用输入参数作为变量。 The release notes for 9.0:
输入参数现在就像一个初始化为传入值的局部变量。
CREATE OR REPLACE FUNCTION get(_param_id integer)
RETURNS integer AS
$func$
BEGIN
SELECT INTO _param1 col1 FROM TABLE WHERE id = _param1;
RETURN _param1;
-- Also possible, but discouraged:
-- $1 := col1 FROM TABLE WHERE id = $1;
-- RETURN $1;
END
$func$ LANGUAGE plpgsql;
使用最后一个隐式使用变量,但您没有DECLARE
显式地(根据请求)。
DEFAULT
参数INOUT
值
这是一个特例。
CREATE OR REPLACE FUNCTION get(_param_id integer, INOUT _col1 integer = 123)
RETURNS integer AS
$func$
BEGIN
-- You can assign some (other) value to _col1:
-- SELECT INTO _col1 col1 FROM TABLE WHERE id = _param_id;
-- If you don't, the DEFAULT 123 will be returned.
END
$func$ LANGUAGE plpgsql;
INOUT _col1 integer = 123
是INOUT _col1 integer DEFAULT 123
的简短表示法。详细说明:
CREATE OR REPLACE FUNCTION get(_param_id integer)
RETURNS integer AS
$func$
SELECT col1 FROM TABLE WHERE id = _param_id;
-- use positional reference $1 instead of param name in Postgres 9.1 or older
$func$
LANGUAGE sql;
答案 1 :(得分:1)
CREATE or REPLACE FUNCTION get(i integer)
RETURNS integer as $id$
DECLARE
id integer;
BEGIN
SELECT column_id INTO id FROM table_name WHERE column_id=i;
RETURN id;
END;
$id$ LANGUAGE plpgsql;