Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

postgresql - Can I make a plpgsql function return an integer without using a variable?

Something like this:

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;

I would like to avoid a DECLARE just for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you can. There are a number of ways.

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

2) Use an OUT or INOUT parameter

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;

More in the manual here.

3) (Ab)use IN parameter

Since Postgres 9.0 you can also use input parameters as variables. The release notes for 9.0:

An input parameter now acts like a local variable initialized to the passed-in value.

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;

With the last ones you do use a variable implicitly, but you don't have to DECLARE it explicitly (as requested).

4) Use a DEFAULT value with an INOUT parameter

This is a bit of a special case. The function body can be empty.

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 is short notation for INOUT _col1 integer DEFAULT 123. More:

5) Use a plain SQL function instead

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...