ok

Mini Shell

Direktori : /opt/alt/postgresql11/usr/share/doc/alt-postgresql11-9.2.24/html/
Upload File :
Current File : //opt/alt/postgresql11/usr/share/doc/alt-postgresql11-9.2.24/html/xfunc-sql.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>Query Language (SQL) Functions</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.24 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Extending SQL"
HREF="extend.html"><LINK
REL="PREVIOUS"
TITLE="User-defined Functions"
HREF="xfunc.html"><LINK
REL="NEXT"
TITLE="Function Overloading"
HREF="xfunc-overload.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-11-06T22:43:11"></HEAD
><BODY
CLASS="SECT1"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.2.24 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="User-defined Functions"
HREF="xfunc.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="extend.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
>Chapter 35. Extending <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
></TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="Function Overloading"
HREF="xfunc-overload.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="XFUNC-SQL"
>35.4. Query Language (<ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
>) Functions</A
></H1
><P
>    SQL functions execute an arbitrary list of SQL statements, returning
    the result of the last query in the list.
    In the simple (non-set)
    case, the first row of the last query's result will be returned.
    (Bear in mind that <SPAN
CLASS="QUOTE"
>"the first row"</SPAN
> of a multirow
    result is not well-defined unless you use <TT
CLASS="LITERAL"
>ORDER BY</TT
>.)
    If the last query happens
    to return no rows at all, the null value will be returned.
   </P
><P
>    Alternatively, an SQL function can be declared to return a set,
    by specifying the function's return type as <TT
CLASS="LITERAL"
>SETOF
    <TT
CLASS="REPLACEABLE"
><I
>sometype</I
></TT
></TT
>, or equivalently by declaring it as
    <TT
CLASS="LITERAL"
>RETURNS TABLE(<TT
CLASS="REPLACEABLE"
><I
>columns</I
></TT
>)</TT
>.  In this case
    all rows of the last query's result are returned.  Further details appear
    below.
   </P
><P
>    The body of an SQL function must be a list of SQL
    statements separated by semicolons.  A semicolon after the last
    statement is optional.  Unless the function is declared to return
    <TT
CLASS="TYPE"
>void</TT
>, the last statement must be a <TT
CLASS="COMMAND"
>SELECT</TT
>,
    or an <TT
CLASS="COMMAND"
>INSERT</TT
>, <TT
CLASS="COMMAND"
>UPDATE</TT
>, or <TT
CLASS="COMMAND"
>DELETE</TT
>
    that has a <TT
CLASS="LITERAL"
>RETURNING</TT
> clause.
   </P
><P
>     Any collection of commands in the  <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
>
     language can be packaged together and defined as a function.
     Besides <TT
CLASS="COMMAND"
>SELECT</TT
> queries, the commands can include data
     modification queries (<TT
CLASS="COMMAND"
>INSERT</TT
>,
     <TT
CLASS="COMMAND"
>UPDATE</TT
>, and <TT
CLASS="COMMAND"
>DELETE</TT
>), as well as
     other SQL commands. (You cannot use transaction control commands, e.g.
     <TT
CLASS="COMMAND"
>COMMIT</TT
>, <TT
CLASS="COMMAND"
>SAVEPOINT</TT
>, and some utility
     commands, e.g.  <TT
CLASS="LITERAL"
>VACUUM</TT
>, in <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> functions.)
     However, the final command
     must be a <TT
CLASS="COMMAND"
>SELECT</TT
> or have a <TT
CLASS="LITERAL"
>RETURNING</TT
>
     clause that returns whatever is
     specified as the function's return type.  Alternatively, if you
     want to define a SQL function that performs actions but has no
     useful value to return, you can define it as returning <TT
CLASS="TYPE"
>void</TT
>.
     For example, this function removes rows with negative salaries from
     the <TT
CLASS="LITERAL"
>emp</TT
> table:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION clean_emp() RETURNS void AS '
    DELETE FROM emp
        WHERE salary &lt; 0;
' LANGUAGE SQL;

SELECT clean_emp();

 clean_emp
-----------

(1 row)</PRE
><P>
    </P
><P
>    The syntax of the <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command requires
    the function body to be written as a string constant.  It is usually
    most convenient to use dollar quoting (see <A
HREF="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING"
>Section 4.1.2.4</A
>) for the string constant.
    If you choose to use regular single-quoted string constant syntax,
    you must double single quote marks (<TT
CLASS="LITERAL"
>'</TT
>) and backslashes
    (<TT
CLASS="LITERAL"
>\</TT
>) (assuming escape string syntax) in the body of
    the function (see <A
HREF="sql-syntax-lexical.html#SQL-SYNTAX-STRINGS"
>Section 4.1.2.1</A
>).
   </P
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-FUNCTION-ARGUMENTS"
>35.4.1. Arguments for <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions</A
></H2
><P
>     Arguments of a SQL function can be referenced in the function
     body using either names or numbers.  Examples of both methods appear
     below.
    </P
><P
>     To use a name, declare the function argument as having a name, and
     then just write that name in the function body.  If the argument name
     is the same as any column name in the current SQL command within the
     function, the column name will take precedence.  To override this,
     qualify the argument name with the name of the function itself, that is
     <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
>.<TT
CLASS="REPLACEABLE"
><I
>argument_name</I
></TT
></TT
>.
     (If this would conflict with a qualified column name, again the column
     name wins.  You can avoid the ambiguity by choosing a different alias for
     the table within the SQL command.)
    </P
><P
>     In the older numeric approach, arguments are referenced using the syntax
     <TT
CLASS="LITERAL"
>$<TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
></TT
>: <TT
CLASS="LITERAL"
>$1</TT
> refers to the first input
     argument, <TT
CLASS="LITERAL"
>$2</TT
> to the second, and so on.  This will work
     whether or not the particular argument was declared with a name.
    </P
><P
>     If an argument is of a composite type, then the dot notation,
     e.g., <TT
CLASS="LITERAL"
>argname.fieldname</TT
> or
     <TT
CLASS="LITERAL"
>$1.fieldname</TT
>, can be used to access attributes of the
     argument.  Again, you might need to qualify the argument's name with the
     function name to make the form with an argument name unambiguous.
    </P
><P
>     SQL function arguments can only be used as data values,
     not as identifiers.  Thus for example this is reasonable:
</P><PRE
CLASS="PROGRAMLISTING"
>INSERT INTO mytable VALUES ($1);</PRE
><P>
but this will not work:
</P><PRE
CLASS="PROGRAMLISTING"
>INSERT INTO $1 VALUES (42);</PRE
><P>
    </P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>      The ability to use names to reference SQL function arguments was added
      in <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> 9.2.  Functions to be used in
      older servers must use the <TT
CLASS="LITERAL"
>$<TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
></TT
> notation.
     </P
></BLOCKQUOTE
></DIV
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-BASE-FUNCTIONS"
>35.4.2. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions on Base Types</A
></H2
><P
>     The simplest possible <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> function has no arguments and
     simply returns a base type, such as <TT
CLASS="TYPE"
>integer</TT
>:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION one() RETURNS integer AS $$
    SELECT 1 AS result;
$$ LANGUAGE SQL;

-- Alternative syntax for string literal:
CREATE FUNCTION one() RETURNS integer AS '
    SELECT 1 AS result;
' LANGUAGE SQL;

SELECT one();

 one
-----
   1</PRE
><P>
    </P
><P
>     Notice that we defined a column alias within the function body for the result of the function
     (with  the  name <TT
CLASS="LITERAL"
>result</TT
>),  but this column alias is not visible
     outside the function.  Hence,  the  result  is labeled <TT
CLASS="LITERAL"
>one</TT
>
     instead of <TT
CLASS="LITERAL"
>result</TT
>.
    </P
><P
>     It is almost as easy to define <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> functions
     that take base types as arguments:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION add_em(x integer, y integer) RETURNS integer AS $$
    SELECT x + y;
$$ LANGUAGE SQL;

SELECT add_em(1, 2) AS answer;

 answer
--------
      3</PRE
><P>
    </P
><P
>     Alternatively, we could dispense with names for the arguments and
     use numbers:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$
    SELECT $1 + $2;
$$ LANGUAGE SQL;

SELECT add_em(1, 2) AS answer;

 answer
--------
      3</PRE
><P>
    </P
><P
>     Here is a more useful function, which might be used to debit a
     bank account:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS integer AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno;
    SELECT 1;
$$ LANGUAGE SQL;</PRE
><P>

     A user could execute this function to debit account 17 by $100.00 as
     follows:

</P><PRE
CLASS="PROGRAMLISTING"
>SELECT tf1(17, 100.0);</PRE
><P>
    </P
><P
>     In this example, we chose the name <TT
CLASS="LITERAL"
>accountno</TT
> for the first
     argument, but this is the same as the name of a column in the
     <TT
CLASS="LITERAL"
>bank</TT
> table.  Within the <TT
CLASS="COMMAND"
>UPDATE</TT
> command,
     <TT
CLASS="LITERAL"
>accountno</TT
> refers to the column <TT
CLASS="LITERAL"
>bank.accountno</TT
>,
     so <TT
CLASS="LITERAL"
>tf1.accountno</TT
> must be used to refer to the argument.
     We could of course avoid this by using a different name for the argument.
    </P
><P
>     In practice one would probably like a more useful result from the
     function than a constant 1, so a more likely definition
     is:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS integer AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno;
    SELECT balance FROM bank WHERE accountno = tf1.accountno;
$$ LANGUAGE SQL;</PRE
><P>

     which adjusts the balance and returns the new balance.
     The same thing could be done in one command using <TT
CLASS="LITERAL"
>RETURNING</TT
>:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS integer AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno
    RETURNING balance;
$$ LANGUAGE SQL;</PRE
><P>
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-COMPOSITE-FUNCTIONS"
>35.4.3. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions on Composite Types</A
></H2
><P
>     When writing functions with arguments of composite types, we must not
     only specify which argument we want but also the desired attribute
     (field) of that argument.  For example, suppose that
     <TT
CLASS="TYPE"
>emp</TT
> is a table containing employee data, and therefore
     also the name of the composite type of each row of the table.  Here
     is a function <CODE
CLASS="FUNCTION"
>double_salary</CODE
> that computes what someone's
     salary would be if it were doubled:

</P><PRE
CLASS="SCREEN"
>CREATE TABLE emp (
    name        text,
    salary      numeric,
    age         integer,
    cubicle     point
);

INSERT INTO emp VALUES ('Bill', 4200, 45, '(2,1)');

CREATE FUNCTION double_salary(emp) RETURNS numeric AS $$
    SELECT $1.salary * 2 AS salary;
$$ LANGUAGE SQL;

SELECT name, double_salary(emp.*) AS dream
    FROM emp
    WHERE emp.cubicle ~= point '(2,1)';

 name | dream
------+-------
 Bill |  8400</PRE
><P>
    </P
><P
>     Notice the use of the syntax <TT
CLASS="LITERAL"
>$1.salary</TT
>
     to select one field of the argument row value.  Also notice
     how the calling <TT
CLASS="COMMAND"
>SELECT</TT
> command
     uses <TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
><TT
CLASS="LITERAL"
>.*</TT
> to select
     the entire current row of a table as a composite value.  The table
     row can alternatively be referenced using just the table name,
     like this:
</P><PRE
CLASS="SCREEN"
>SELECT name, double_salary(emp) AS dream
    FROM emp
    WHERE emp.cubicle ~= point '(2,1)';</PRE
><P>
     but this usage is deprecated since it's easy to get confused.
     (See <A
HREF="rowtypes.html#ROWTYPES-USAGE"
>Section 8.16.5</A
> for details about these
     two notations for the composite value of a table row.)
    </P
><P
>     Sometimes it is handy to construct a composite argument value
     on-the-fly.  This can be done with the <TT
CLASS="LITERAL"
>ROW</TT
> construct.
     For example, we could adjust the data being passed to the function:
</P><PRE
CLASS="SCREEN"
>SELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream
    FROM emp;</PRE
><P>
    </P
><P
>     It is also possible to build a function that returns a composite type.
     This is an example of a function
     that returns a single <TT
CLASS="TYPE"
>emp</TT
> row:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION new_emp() RETURNS emp AS $$
    SELECT text 'None' AS name,
        1000.0 AS salary,
        25 AS age,
        point '(2,2)' AS cubicle;
$$ LANGUAGE SQL;</PRE
><P>

     In this example we have specified each of  the  attributes
     with  a  constant value, but any computation
     could have been substituted for these constants.
    </P
><P
>     Note two important things about defining the function:

     <P
></P
></P><UL
><LI
><P
>        The select list order in the query must be exactly the same as
        that in which the columns appear in the table associated
        with the composite type.  (Naming the columns, as we did above,
        is irrelevant to the system.)
       </P
></LI
><LI
><P
>        You must typecast the expressions to match the
        definition of the composite type, or you will get errors like this:
</P><PRE
CLASS="SCREEN"
><SAMP
CLASS="COMPUTEROUTPUT"
>ERROR:  function declared to return emp returns varchar instead of text at column 1</SAMP
></PRE
><P>
       </P
></LI
></UL
><P>
    </P
><P
>     A different way to define the same function is:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION new_emp() RETURNS emp AS $$
    SELECT ROW('None', 1000.0, 25, '(2,2)')::emp;
$$ LANGUAGE SQL;</PRE
><P>

     Here we wrote a <TT
CLASS="COMMAND"
>SELECT</TT
> that returns just a single
     column of the correct composite type.  This isn't really better
     in this situation, but it is a handy alternative in some cases
     &mdash; for example, if we need to compute the result by calling
     another function that returns the desired composite value.
    </P
><P
>     We could call this function directly either by using it in
     a value expression:

</P><PRE
CLASS="SCREEN"
>SELECT new_emp();

         new_emp
--------------------------
 (None,1000.0,25,"(2,2)")</PRE
><P>

     or by calling it as a table function:

</P><PRE
CLASS="SCREEN"
>SELECT * FROM new_emp();

 name | salary | age | cubicle
------+--------+-----+---------
 None | 1000.0 |  25 | (2,2)</PRE
><P>

     The second way is described more fully in <A
HREF="xfunc-sql.html#XFUNC-SQL-TABLE-FUNCTIONS"
>Section 35.4.7</A
>.
    </P
><P
>     When you use a function that returns a composite type,
     you might want only one field (attribute) from its result.
     You can do that with syntax like this:

</P><PRE
CLASS="SCREEN"
>SELECT (new_emp()).name;

 name
------
 None</PRE
><P>

     The extra parentheses are needed to keep the parser from getting
     confused.  If you try to do it without them, you get something like this:

</P><PRE
CLASS="SCREEN"
>SELECT new_emp().name;
ERROR:  syntax error at or near "."
LINE 1: SELECT new_emp().name;
                        ^</PRE
><P>
    </P
><P
>     Another option is to use functional notation for extracting an attribute:

</P><PRE
CLASS="SCREEN"
>SELECT name(new_emp());

 name
------
 None</PRE
><P>

     As explained in <A
HREF="rowtypes.html#ROWTYPES-USAGE"
>Section 8.16.5</A
>, the field notation and
     functional notation are equivalent.
    </P
><P
>     Another way to use a function returning a composite type is to pass the
     result to another function that accepts the correct row type as input:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION getname(emp) RETURNS text AS $$
    SELECT $1.name;
$$ LANGUAGE SQL;

SELECT getname(new_emp());
 getname
---------
 None
(1 row)</PRE
><P>
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-OUTPUT-PARAMETERS"
>35.4.4. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions with Output Parameters</A
></H2
><P
>     An alternative way of describing a function's results is to define it
     with <I
CLASS="FIRSTTERM"
>output parameters</I
>, as in this example:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)
AS 'SELECT x + y'
LANGUAGE SQL;

SELECT add_em(3,7);
 add_em
--------
     10
(1 row)</PRE
><P>

     This is not essentially different from the version of <TT
CLASS="LITERAL"
>add_em</TT
>
     shown in <A
HREF="xfunc-sql.html#XFUNC-SQL-BASE-FUNCTIONS"
>Section 35.4.2</A
>.  The real value of
     output parameters is that they provide a convenient way of defining
     functions that return several columns.  For example,

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)
AS 'SELECT x + y, x * y'
LANGUAGE SQL;

 SELECT * FROM sum_n_product(11,42);
 sum | product
-----+---------
  53 |     462
(1 row)</PRE
><P>

     What has essentially happened here is that we have created an anonymous
     composite type for the result of the function.  The above example has
     the same end result as

</P><PRE
CLASS="SCREEN"
>CREATE TYPE sum_prod AS (sum int, product int);

CREATE FUNCTION sum_n_product (int, int) RETURNS sum_prod
AS 'SELECT $1 + $2, $1 * $2'
LANGUAGE SQL;</PRE
><P>

     but not having to bother with the separate composite type definition
     is often handy.  Notice that the names attached to the output parameters
     are not just decoration, but determine the column names of the anonymous
     composite type.  (If you omit a name for an output parameter, the
     system will choose a name on its own.)
    </P
><P
>     Notice that output parameters are not included in the calling argument
     list when invoking such a function from SQL.  This is because
     <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> considers only the input
     parameters to define the function's calling signature.  That means
     also that only the input parameters matter when referencing the function
     for purposes such as dropping it.  We could drop the above function
     with either of

</P><PRE
CLASS="SCREEN"
>DROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);
DROP FUNCTION sum_n_product (int, int);</PRE
><P>
    </P
><P
>     Parameters can be marked as <TT
CLASS="LITERAL"
>IN</TT
> (the default),
     <TT
CLASS="LITERAL"
>OUT</TT
>, <TT
CLASS="LITERAL"
>INOUT</TT
>, or <TT
CLASS="LITERAL"
>VARIADIC</TT
>.
     An <TT
CLASS="LITERAL"
>INOUT</TT
>
     parameter serves as both an input parameter (part of the calling
     argument list) and an output parameter (part of the result record type).
     <TT
CLASS="LITERAL"
>VARIADIC</TT
> parameters are input parameters, but are treated
     specially as described next.
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-VARIADIC-FUNCTIONS"
>35.4.5. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions with Variable Numbers of Arguments</A
></H2
><P
>     <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> functions can be declared to accept
     variable numbers of arguments, so long as all the <SPAN
CLASS="QUOTE"
>"optional"</SPAN
>
     arguments are of the same data type.  The optional arguments will be
     passed to the function as an array.  The function is declared by
     marking the last parameter as <TT
CLASS="LITERAL"
>VARIADIC</TT
>; this parameter
     must be declared as being of an array type.  For example:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$
    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;

SELECT mleast(10, -1, 5, 4.4);
 mleast 
--------
     -1
(1 row)</PRE
><P>

     Effectively, all the actual arguments at or beyond the
     <TT
CLASS="LITERAL"
>VARIADIC</TT
> position are gathered up into a one-dimensional
     array, as if you had written

</P><PRE
CLASS="SCREEN"
>SELECT mleast(ARRAY[10, -1, 5, 4.4]);    -- doesn't work</PRE
><P>

     You can't actually write that, though &mdash; or at least, it will
     not match this function definition.  A parameter marked
     <TT
CLASS="LITERAL"
>VARIADIC</TT
> matches one or more occurrences of its element
     type, not of its own type.
    </P
><P
>     Sometimes it is useful to be able to pass an already-constructed array
     to a variadic function; this is particularly handy when one variadic
     function wants to pass on its array parameter to another one.  You can
     do that by specifying <TT
CLASS="LITERAL"
>VARIADIC</TT
> in the call:

</P><PRE
CLASS="SCREEN"
>SELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);</PRE
><P>

     This prevents expansion of the function's variadic parameter into its
     element type, thereby allowing the array argument value to match
     normally.  <TT
CLASS="LITERAL"
>VARIADIC</TT
> can only be attached to the last
     actual argument of a function call.
    </P
><P
>     Specifying <TT
CLASS="LITERAL"
>VARIADIC</TT
> in the call is also the only way to
     pass an empty array to a variadic function, for example:

</P><PRE
CLASS="SCREEN"
>SELECT mleast(VARIADIC ARRAY[]::numeric[]);</PRE
><P>

     Simply writing <TT
CLASS="LITERAL"
>SELECT mleast()</TT
> does not work because a
     variadic parameter must match at least one actual argument.
     (You could define a second function also named <TT
CLASS="LITERAL"
>mleast</TT
>,
     with no parameters, if you wanted to allow such calls.)
    </P
><P
>     The array element parameters generated from a variadic parameter are
     treated as not having any names of their own.  This means it is not
     possible to call a variadic function using named arguments (<A
HREF="sql-syntax-calling-funcs.html"
>Section 4.3</A
>), except when you specify
     <TT
CLASS="LITERAL"
>VARIADIC</TT
>.  For example, this will work:

</P><PRE
CLASS="SCREEN"
>SELECT mleast(VARIADIC arr := ARRAY[10, -1, 5, 4.4]);</PRE
><P>

     but not these:

</P><PRE
CLASS="SCREEN"
>SELECT mleast(arr := 10);
SELECT mleast(arr := ARRAY[10, -1, 5, 4.4]);</PRE
><P>
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-PARAMETER-DEFAULTS"
>35.4.6. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions with Default Values for Arguments</A
></H2
><P
>     Functions can be declared with default values for some or all input
     arguments.  The default values are inserted whenever the function is
     called with insufficiently many actual arguments.  Since arguments
     can only be omitted from the end of the actual argument list, all
     parameters after a parameter with a default value have to have
     default values as well.  (Although the use of named argument notation
     could allow this restriction to be relaxed, it's still enforced so that
     positional argument notation works sensibly.)
    </P
><P
>     For example:
</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)
RETURNS int
LANGUAGE SQL
AS $$
    SELECT $1 + $2 + $3;
$$;

SELECT foo(10, 20, 30);
 foo 
-----
  60
(1 row)

SELECT foo(10, 20);
 foo 
-----
  33
(1 row)

SELECT foo(10);
 foo 
-----
  15
(1 row)

SELECT foo();  -- fails since there is no default for the first argument
ERROR:  function foo() does not exist</PRE
><P>
     The <TT
CLASS="LITERAL"
>=</TT
> sign can also be used in place of the
     key word <TT
CLASS="LITERAL"
>DEFAULT</TT
>.
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-TABLE-FUNCTIONS"
>35.4.7. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions as Table Sources</A
></H2
><P
>     All SQL functions can be used in the <TT
CLASS="LITERAL"
>FROM</TT
> clause of a query,
     but it is particularly useful for functions returning composite types.
     If the function is defined to return a base type, the table function
     produces a one-column table.  If the function is defined to return
     a composite type, the table function produces a column for each attribute
     of the composite type.
    </P
><P
>     Here is an example:

</P><PRE
CLASS="SCREEN"
>CREATE TABLE foo (fooid int, foosubid int, fooname text);
INSERT INTO foo VALUES (1, 1, 'Joe');
INSERT INTO foo VALUES (1, 2, 'Ed');
INSERT INTO foo VALUES (2, 1, 'Mary');

CREATE FUNCTION getfoo(int) RETURNS foo AS $$
    SELECT * FROM foo WHERE fooid = $1;
$$ LANGUAGE SQL;

SELECT *, upper(fooname) FROM getfoo(1) AS t1;

 fooid | foosubid | fooname | upper
-------+----------+---------+-------
     1 |        1 | Joe     | JOE
(1 row)</PRE
><P>

     As the example shows, we can work with the columns of the function's
     result just the same as if they were columns of a regular table.
    </P
><P
>     Note that we only got one row out of the function.  This is because
     we did not use <TT
CLASS="LITERAL"
>SETOF</TT
>.  That is described in the next section.
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-FUNCTIONS-RETURNING-SET"
>35.4.8. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions Returning Sets</A
></H2
><P
>     When an SQL function is declared as returning <TT
CLASS="LITERAL"
>SETOF
     <TT
CLASS="REPLACEABLE"
><I
>sometype</I
></TT
></TT
>, the function's final
     query is executed to completion, and each row it
     outputs is returned as an element of the result set.
    </P
><P
>     This feature is normally used when calling the function in the <TT
CLASS="LITERAL"
>FROM</TT
>
     clause.  In this case each row returned by the function becomes
     a row of the table seen by the query.  For example, assume that
     table <TT
CLASS="LITERAL"
>foo</TT
> has the same contents as above, and we say:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$
    SELECT * FROM foo WHERE fooid = $1;
$$ LANGUAGE SQL;

SELECT * FROM getfoo(1) AS t1;</PRE
><P>

     Then we would get:
</P><PRE
CLASS="SCREEN"
> fooid | foosubid | fooname
-------+----------+---------
     1 |        1 | Joe
     1 |        2 | Ed
(2 rows)</PRE
><P>
    </P
><P
>     It is also possible to return multiple rows with the columns defined by
     output parameters, like this:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE TABLE tab (y int, z int);
INSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);

CREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)
RETURNS SETOF record
AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

SELECT * FROM sum_n_product_with_tab(10);
 sum | product
-----+---------
  11 |      10
  13 |      30
  15 |      50
  17 |      70
(4 rows)</PRE
><P>

     The key point here is that you must write <TT
CLASS="LITERAL"
>RETURNS SETOF record</TT
>
     to indicate that the function returns multiple rows instead of just one.
     If there is only one output parameter, write that parameter's type
     instead of <TT
CLASS="TYPE"
>record</TT
>.
    </P
><P
>     Currently, functions returning sets can also be called in the select list
     of a query.  For each row that the query
     generates by itself, the function returning set is invoked, and an output
     row is generated for each element of the function's result set. Note,
     however, that this capability is deprecated and might be removed in future
     releases. The following is an example function returning a set from the
     select list:

</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$
    SELECT name FROM nodes WHERE parent = $1
$$ LANGUAGE SQL;

SELECT * FROM nodes;
   name    | parent
-----------+--------
 Top       |
 Child1    | Top
 Child2    | Top
 Child3    | Top
 SubChild1 | Child1
 SubChild2 | Child1
(6 rows)

SELECT listchildren('Top');
 listchildren
--------------
 Child1
 Child2
 Child3
(3 rows)

SELECT name, listchildren(name) FROM nodes;
  name  | listchildren
--------+--------------
 Top    | Child1
 Top    | Child2
 Top    | Child3
 Child1 | SubChild1
 Child1 | SubChild2
(5 rows)</PRE
><P>

     In the last <TT
CLASS="COMMAND"
>SELECT</TT
>,
     notice that no output row appears for <TT
CLASS="LITERAL"
>Child2</TT
>, <TT
CLASS="LITERAL"
>Child3</TT
>, etc.
     This happens because <CODE
CLASS="FUNCTION"
>listchildren</CODE
> returns an empty set
     for those arguments, so no result rows are generated.
    </P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>      If a function's last command is <TT
CLASS="COMMAND"
>INSERT</TT
>, <TT
CLASS="COMMAND"
>UPDATE</TT
>,
      or <TT
CLASS="COMMAND"
>DELETE</TT
> with <TT
CLASS="LITERAL"
>RETURNING</TT
>, that command will
      always be executed to completion, even if the function is not declared
      with <TT
CLASS="LITERAL"
>SETOF</TT
> or the calling query does not fetch all the
      result rows.  Any extra rows produced by the <TT
CLASS="LITERAL"
>RETURNING</TT
>
      clause are silently dropped, but the commanded table modifications
      still happen (and are all completed before returning from the function).
     </P
></BLOCKQUOTE
></DIV
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="XFUNC-SQL-FUNCTIONS-RETURNING-TABLE"
>35.4.9. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions Returning <TT
CLASS="LITERAL"
>TABLE</TT
></A
></H2
><P
>     There is another way to declare a function as returning a set,
     which is to use the syntax
     <TT
CLASS="LITERAL"
>RETURNS TABLE(<TT
CLASS="REPLACEABLE"
><I
>columns</I
></TT
>)</TT
>.
     This is equivalent to using one or more <TT
CLASS="LITERAL"
>OUT</TT
> parameters plus
     marking the function as returning <TT
CLASS="LITERAL"
>SETOF record</TT
> (or
     <TT
CLASS="LITERAL"
>SETOF</TT
> a single output parameter's type, as appropriate).
     This notation is specified in recent versions of the SQL standard, and
     thus may be more portable than using <TT
CLASS="LITERAL"
>SETOF</TT
>.
    </P
><P
>     For example, the preceding sum-and-product example could also be
     done this way:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;</PRE
><P>

     It is not allowed to use explicit <TT
CLASS="LITERAL"
>OUT</TT
> or <TT
CLASS="LITERAL"
>INOUT</TT
>
     parameters with the <TT
CLASS="LITERAL"
>RETURNS TABLE</TT
> notation &mdash; you must
     put all the output columns in the <TT
CLASS="LITERAL"
>TABLE</TT
> list.
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN52570"
>35.4.10. Polymorphic <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions</A
></H2
><P
>     <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> functions can be declared to accept and
     return the polymorphic types <TT
CLASS="TYPE"
>anyelement</TT
>,
     <TT
CLASS="TYPE"
>anyarray</TT
>, <TT
CLASS="TYPE"
>anynonarray</TT
>,
     <TT
CLASS="TYPE"
>anyenum</TT
>, and <TT
CLASS="TYPE"
>anyrange</TT
>.  See <A
HREF="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC"
>Section 35.2.5</A
> for a more detailed
     explanation of polymorphic functions. Here is a polymorphic
     function <CODE
CLASS="FUNCTION"
>make_array</CODE
> that builds up an array
     from two arbitrary data type elements:
</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$
    SELECT ARRAY[$1, $2];
$$ LANGUAGE SQL;

SELECT make_array(1, 2) AS intarray, make_array('a'::text, 'b') AS textarray;
 intarray | textarray
----------+-----------
 {1,2}    | {a,b}
(1 row)</PRE
><P>
    </P
><P
>     Notice the use of the typecast <TT
CLASS="LITERAL"
>'a'::text</TT
>
     to specify that the argument is of type <TT
CLASS="TYPE"
>text</TT
>. This is
     required if the argument is just a string literal, since otherwise
     it would be treated as type
     <TT
CLASS="TYPE"
>unknown</TT
>, and array of <TT
CLASS="TYPE"
>unknown</TT
> is not a valid
     type.
     Without the typecast, you will get errors like this:
</P><PRE
CLASS="SCREEN"
><SAMP
CLASS="COMPUTEROUTPUT"
>ERROR:  could not determine polymorphic type because input has type "unknown"</SAMP
></PRE
><P>
    </P
><P
>     It is permitted to have polymorphic arguments with a fixed
     return type, but the converse is not. For example:
</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$
    SELECT $1 &gt; $2;
$$ LANGUAGE SQL;

SELECT is_greater(1, 2);
 is_greater
------------
 f
(1 row)

CREATE FUNCTION invalid_func() RETURNS anyelement AS $$
    SELECT 1;
$$ LANGUAGE SQL;
ERROR:  cannot determine result data type
DETAIL:  A function returning a polymorphic type must have at least one polymorphic argument.</PRE
><P>
    </P
><P
>     Polymorphism can be used with functions that have output arguments.
     For example:
</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)
AS 'select $1, array[$1,$1]' LANGUAGE SQL;

SELECT * FROM dup(22);
 f2 |   f3
----+---------
 22 | {22,22}
(1 row)</PRE
><P>
    </P
><P
>     Polymorphism can also be used with variadic functions.
     For example:
</P><PRE
CLASS="SCREEN"
>CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;

SELECT anyleast(10, -1, 5, 4);
 anyleast 
----------
       -1
(1 row)

SELECT anyleast('abc'::text, 'def');
 anyleast 
----------
 abc
(1 row)

CREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$
    SELECT array_to_string($2, $1);
$$ LANGUAGE SQL;

SELECT concat_values('|', 1, 4, 2);
 concat_values 
---------------
 1|4|2
(1 row)</PRE
><P>
    </P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN52596"
>35.4.11. <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> Functions with Collations</A
></H2
><P
>     When a SQL function has one or more parameters of collatable data types,
     a collation is identified for each function call depending on the
     collations assigned to the actual arguments, as described in <A
HREF="collation.html"
>Section 22.2</A
>.  If a collation is successfully identified
     (i.e., there are no conflicts of implicit collations among the arguments)
     then all the collatable parameters are treated as having that collation
     implicitly.  This will affect the behavior of collation-sensitive
     operations within the function.  For example, using the
     <CODE
CLASS="FUNCTION"
>anyleast</CODE
> function described above, the result of
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT anyleast('abc'::text, 'ABC');</PRE
><P>
     will depend on the database's default collation.  In <TT
CLASS="LITERAL"
>C</TT
> locale
     the result will be <TT
CLASS="LITERAL"
>ABC</TT
>, but in many other locales it will
     be <TT
CLASS="LITERAL"
>abc</TT
>.  The collation to use can be forced by adding
     a <TT
CLASS="LITERAL"
>COLLATE</TT
> clause to any of the arguments, for example
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT anyleast('abc'::text, 'ABC' COLLATE "C");</PRE
><P>
     Alternatively, if you wish a function to operate with a particular
     collation regardless of what it is called with, insert
     <TT
CLASS="LITERAL"
>COLLATE</TT
> clauses as needed in the function definition.
     This version of <CODE
CLASS="FUNCTION"
>anyleast</CODE
> would always use <TT
CLASS="LITERAL"
>en_US</TT
>
     locale to compare strings:
</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
    SELECT min($1[i] COLLATE "en_US") FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;</PRE
><P>
     But note that this will throw an error if applied to a non-collatable
     data type.
    </P
><P
>     If no common collation can be identified among the actual arguments,
     then a SQL function treats its parameters as having their data types'
     default collation (which is usually the database's default collation,
     but could be different for parameters of domain types).
    </P
><P
>     The behavior of collatable parameters can be thought of as a limited
     form of polymorphism, applicable only to textual data types.
    </P
></DIV
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="xfunc.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="xfunc-overload.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>User-defined Functions</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="extend.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Function Overloading</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>

Zerion Mini Shell 1.0