⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xfunc.sgml

📁 PostgreSQL7.4.6 for Linux
💻 SGML
📖 第 1 页 / 共 5 页
字号:
<!--$Header: /cvsroot/pgsql/doc/src/sgml/xfunc.sgml,v 1.77.2.1 2003/11/12 20:05:14 petere Exp $--> <sect1 id="xfunc">  <title>User-Defined Functions</title>  <indexterm zone="xfunc">   <primary>function</primary>   <secondary>user-defined</secondary>  </indexterm>  <para>   <productname>PostgreSQL</productname> provides four kinds of   functions:   <itemizedlist>    <listitem>     <para>      query language functions (functions written in      <acronym>SQL</acronym>) (<xref linkend="xfunc-sql">)     </para>    </listitem>    <listitem>     <para>      procedural language functions (functions written in, for      example, <application>PL/Tcl</> or <application>PL/pgSQL</>)      (<xref linkend="xfunc-pl">)     </para>    </listitem>    <listitem>     <para>      internal functions (<xref linkend="xfunc-internal">)     </para>    </listitem>    <listitem>     <para>      C-language functions (<xref linkend="xfunc-c">)     </para>    </listitem>   </itemizedlist>  </para>  <para>   Every kind   of  function  can take base types, composite types, or   combinations of these as arguments (parameters).   In  addition,    every kind of function can return a base type or   a composite type.  </para>  <para>   Many kinds of functions can take or return certain pseudo-types   (such as polymorphic types), but the available facilities vary.   Consult the description of each kind of function for more details.  </para>  <para>   It's easiest to define <acronym>SQL</acronym>    functions, so we'll start by discussing those.   Most of the concepts presented for <acronym>SQL</acronym> functions   will carry over to the other types of functions.  </para>  <para>   Throughout this chapter, it can be useful to look at the reference   page of the <command>CREATE FUNCTION</command> command to   understand the examples better.   Some examples from this chapter   can be found in <filename>funcs.sql</filename>    and <filename>funcs.c</filename> in the <filename>src/tutorial</>   directory in the <productname>PostgreSQL</productname> source distribution.  </para>  </sect1>  <sect1 id="xfunc-sql">   <title>Query Language (<acronym>SQL</acronym>) Functions</title>   <indexterm zone="xfunc-sql">    <primary>function</primary>    <secondary>user-defined</secondary>    <tertiary>in SQL</tertiary>   </indexterm>   <para>    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 <quote>the first row</quote> of a multirow    result is not well-defined unless you use <literal>ORDER BY</>.)    If the last query happens    to return no rows at all, the null value will be returned.   </para>   <para>    <indexterm><primary>SETOF</><seealso>function</></> Alternatively,    an SQL function may be declared to return a set, by specifying the    function's return type as <literal>SETOF    <replaceable>sometype</></literal>.<indexterm><primary>SETOF</></>    In this case all rows of the last query's result are returned.    Further details appear below.   </para>   <para>    The body of an SQL function should be a list of one or more SQL    statements separated by semicolons.  Note that because the syntax    of the <command>CREATE FUNCTION</command> command requires the body of the    function to be enclosed in single quotes, single quote marks    (<literal>'</>) used    in the body of the function must be escaped, by writing two single    quotes (<literal>''</>) or a backslash (<literal>\'</>) where each    quote is desired.   </para>   <para>    Arguments to the SQL function may be referenced in the function    body using the syntax <literal>$<replaceable>n</></>: <literal>$1</> refers to    the first argument, <literal>$2</> to the second, and so on.  If an argument    is of a composite type, then the dot notation,    e.g., <literal>$1.name</literal>, may be used to access attributes    of the argument.   </para>   <sect2>    <title><acronym>SQL</acronym> Functions on Base Types</title>    <para>     The simplest possible <acronym>SQL</acronym> function has no arguments and     simply returns a base type, such as <type>integer</type>:     <screen>CREATE FUNCTION one() RETURNS integer AS '    SELECT 1 AS result;' LANGUAGE SQL;SELECT one(); one-----   1</screen>    </para>    <para>     Notice that we defined a column alias within the function body for the result of the function     (with  the  name <literal>result</>),  but this column alias is not visible     outside the function.  Hence,  the  result  is labeled <literal>one</>     instead of <literal>result</>.    </para>    <para>     It is almost as easy to define <acronym>SQL</acronym> functions       that take base types as arguments.  In the example below, notice     how we refer to the arguments within the function as <literal>$1</>     and <literal>$2</>.<screen>CREATE FUNCTION add_em(integer, integer) RETURNS integer AS '    SELECT $1 + $2;' LANGUAGE SQL;SELECT add_em(1, 2) AS answer; answer--------      3</screen>    </para>    <para>     Here is a more useful function, which might be used to debit a     bank account:<programlisting>CREATE FUNCTION tf1 (integer, numeric) RETURNS integer AS '    UPDATE bank         SET balance = balance - $2        WHERE accountno = $1;    SELECT 1;' LANGUAGE SQL;</programlisting>     A user could execute this function to debit account 17 by $100.00 as     follows:<programlisting>SELECT tf1(17, 100.0);</programlisting>    </para>    <para>     In practice one would probably like a more useful result from the     function than a constant 1, so a more likely definition     is<programlisting>CREATE FUNCTION tf1 (integer, numeric) RETURNS numeric AS '    UPDATE bank         SET balance = balance - $2        WHERE accountno = $1;    SELECT balance FROM bank WHERE accountno = $1;' LANGUAGE SQL;</programlisting>     which adjusts the balance and returns the new balance.    </para>    <para>     Any collection of commands in the  <acronym>SQL</acronym>     language can be packaged together and defined as a function.     Besides <command>SELECT</command> queries,     the commands can include data modification (i.e.,     <command>INSERT</command>, <command>UPDATE</command>, and     <command>DELETE</command>).  However, the final command      must be a <command>SELECT</command> 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 <type>void</>.     In that case, the function body must not end with a <command>SELECT</command>.     For example:<screen>CREATE FUNCTION clean_emp() RETURNS void AS '    DELETE FROM emp        WHERE salary &lt;= 0;' LANGUAGE SQL;SELECT clean_emp(); clean_emp-----------(1 row)</screen>    </para>   </sect2>   <sect2>    <title><acronym>SQL</acronym> Functions on Composite Types</title>    <para>     When  specifying  functions with arguments of composite     types, we must  not  only  specify  which     argument  we  want (as we did above with <literal>$1</> and <literal>$2</literal>) but     also the attributes of  that  argument.   For  example, suppose that     <type>emp</type> 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 <function>double_salary</function> that computes what someone's     salary would be if it were doubled:<screen>CREATE TABLE emp (    name        text,    salary      integer,    age         integer,    cubicle     point);CREATE FUNCTION double_salary(emp) RETURNS integer 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------+------- Sam  |  2400</screen>    </para>    <para>     Notice the use of the syntax <literal>$1.salary</literal>     to select one field of the argument row value.  Also notice     how the calling <command>SELECT</> command uses a table name to denote     the entire current row of that table as a composite value.  The table     row can alternatively be referenced like this:<screen>SELECT name, double_salary(emp.*) AS dream    FROM emp    WHERE emp.cubicle ~= point '(2,1)';</screen>     which emphasizes its row nature.    </para>    <para>     It is also possible to build a function that returns a composite type.     This is an example of a function      that returns a single <type>emp</type> row:<programlisting>CREATE FUNCTION new_emp() RETURNS emp AS '    SELECT text ''None'' AS name,        1000 AS salary,        25 AS age,        point ''(2,2)'' AS cubicle;' LANGUAGE SQL;</programlisting>     In this example we have specified each of  the  attributes     with  a  constant value, but any computation     could have been substituted for these constants.    </para>    <para>     Note two important things about defining the function:     <itemizedlist>      <listitem>       <para>	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.)       </para>      </listitem>      <listitem>       <para>	You must typecast the expressions to match the	definition of the composite type, or you will get errors like this:<screen><computeroutput>ERROR:  function declared to return emp returns varchar instead of text at column 1</computeroutput></screen>       </para>      </listitem>     </itemizedlist>    </para>         <para>     A function that returns a row (composite type) can be used as a table     function, as described below.  It can also be called in the context     of an SQL expression, but only when you     extract a single attribute out of the row or pass the entire row into     another function that accepts the same composite type.    </para>    <para>     This is an example of extracting an attribute out of a row type:<screen>SELECT (new_emp()).name; name------ None</screen>     We need the extra parentheses to keep the parser from getting confused:<screen>SELECT new_emp().name;ERROR:  syntax error at or near "." at character 17</screen>    </para>    <para>     Another option is to use     functional notation for extracting an attribute.  The  simple  way      to explain this is that we can use the     notations <literal>attribute(table)</>  and  <literal>table.attribute</>     interchangeably.<screen>SELECT name(new_emp()); name------ None</screen><screen>-- This is the same as:-- SELECT emp.name AS youngster FROM emp WHERE emp.age &lt; 30SELECT name(emp) AS youngster    FROM emp    WHERE age(emp) &lt; 30; youngster----------- Sam</screen>    </para>    <para>     The other way to use a function returning a row result is to declare a     second function accepting a row type argument and pass the     result of the first function to it:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -