📄 plpgsql.sgml
字号:
</sect2> </sect1> <sect1 id="plpgsql-structure"> <title>Structure of <application>PL/pgSQL</application></title> <para> <application>PL/pgSQL</application> is a block-structured language. The complete text of a function definition must be a <firstterm>block</>. A block is defined as:<synopsis><optional> <<<replaceable>label</replaceable>>> </optional><optional> DECLARE <replaceable>declarations</replaceable> </optional>BEGIN <replaceable>statements</replaceable>END;</synopsis> </para> <para> Each declaration and each statement within a block is terminated by a semicolon. </para> <para> All key words and identifiers can be written in mixed upper and lower case. Identifiers are implicitly converted to lower-case unless double-quoted. </para> <para> There are two types of comments in <application>PL/pgSQL</>. A double dash (<literal>--</literal>) starts a comment that extends to the end of the line. A <literal>/*</literal> starts a block comment that extends to the next occurrence of <literal>*/</literal>. Block comments cannot be nested, but double dash comments can be enclosed into a block comment and a double dash can hide the block comment delimiters <literal>/*</literal> and <literal>*/</literal>. </para> <para> Any statement in the statement section of a block can be a <firstterm>subblock</>. Subblocks can be used for logical grouping or to localize variables to a small group of statements. </para> <para> The variables declared in the declarations section preceding a block are initialized to their default values every time the block is entered, not only once per function call. For example:<programlisting>CREATE FUNCTION somefunc() RETURNS integer AS 'DECLARE quantity integer := 30;BEGIN RAISE NOTICE ''Quantity here is %'', quantity; -- Quantity here is 30 quantity := 50; -- -- Create a subblock -- DECLARE quantity integer := 80; BEGIN RAISE NOTICE ''Quantity here is %'', quantity; -- Quantity here is 80 END; RAISE NOTICE ''Quantity here is %'', quantity; -- Quantity here is 50 RETURN quantity;END;' LANGUAGE plpgsql;</programlisting> </para> <para> It is important not to confuse the use of <command>BEGIN</>/<command>END</> for grouping statements in <application>PL/pgSQL</> with the database commands for transaction control. <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</> are only for grouping; they do not start or end a transaction. Functions and trigger procedures are always executed within a transaction established by an outer query --- they cannot start or commit transactions, since <productname>PostgreSQL</productname> does not have nested transactions. </para> </sect1> <sect1 id="plpgsql-declarations"> <title>Declarations</title> <para> All variables used in a block must be declared in the declarations section of the block. (The only exception is that the loop variable of a <literal>FOR</> loop iterating over a range of integer values is automatically declared as an integer variable.) </para> <para> <application>PL/pgSQL</> variables can have any SQL data type, such as <type>integer</type>, <type>varchar</type>, and <type>char</type>. </para> <para> Here are some examples of variable declarations:<programlisting>user_id integer;quantity numeric(5);url varchar;myrow tablename%ROWTYPE;myfield tablename.columnname%TYPE;arow RECORD;</programlisting> </para> <para> The general syntax of a variable declaration is:<synopsis><replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;</synopsis> The <literal>DEFAULT</> clause, if given, specifies the initial value assigned to the variable when the block is entered. If the <literal>DEFAULT</> clause is not given then the variable is initialized to the <acronym>SQL</acronym> null value. The <literal>CONSTANT</> option prevents the variable from being assigned to, so that its value remains constant for the duration of the block. If <literal>NOT NULL</> is specified, an assignment of a null value results in a run-time error. All variables declared as <literal>NOT NULL</> must have a nonnull default value specified. </para> <para> The default value is evaluated every time the block is entered. So, for example, assigning <literal>'now'</literal> to a variable of type <type>timestamp</type> causes the variable to have the time of the current function call, not the time when the function was precompiled. </para> <para> Examples:<programlisting>quantity integer DEFAULT 32;url varchar := ''http://mysite.com'';user_id CONSTANT integer := 10;</programlisting> </para> <sect2 id="plpgsql-declaration-aliases"> <title>Aliases for Function Parameters</title><synopsis><replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;</synopsis> <para> Parameters passed to functions are named with the identifiers <literal>$1</literal>, <literal>$2</literal>, etc. Optionally, aliases can be declared for <literal>$<replaceable>n</replaceable></literal> parameter names for increased readability. Either the alias or the numeric identifier can then be used to refer to the parameter value. Some examples:<programlisting>CREATE FUNCTION sales_tax(real) RETURNS real AS 'DECLARE subtotal ALIAS FOR $1;BEGIN RETURN subtotal * 0.06;END;' LANGUAGE plpgsql;CREATE FUNCTION instr(varchar, integer) RETURNS integer AS 'DECLARE v_string ALIAS FOR $1; index ALIAS FOR $2;BEGIN -- some computations hereEND;' LANGUAGE plpgsql;CREATE FUNCTION concat_selected_fields(tablename) RETURNS text AS 'DECLARE in_t ALIAS FOR $1;BEGIN RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;END;' LANGUAGE plpgsql;</programlisting> </para> <para> When the return type of a <application>PL/pgSQL</application> function is declared as a polymorphic type (<type>anyelement</type> or <type>anyarray</type>), a special parameter <literal>$0</literal> is created. Its data type is the actual return type of the function, as deduced from the actual input types (see <xref linkend="extend-types-polymorphic">). This allows the function to access its actual return type as shown in <xref linkend="plpgsql-declaration-type">. <literal>$0</literal> is initialized to null and can be modified by the function, so it can be used to hold the return value if desired, though that is not required. <literal>$0</literal> can also be given an alias. For example, this function works on any data type that has a <literal>+</> operator:<programlisting>CREATE FUNCTION add_three_values(anyelement, anyelement, anyelement)RETURNS anyelement AS 'DECLARE result ALIAS FOR $0; first ALIAS FOR $1; second ALIAS FOR $2; third ALIAS FOR $3;BEGIN result := first + second + third; RETURN result;END;' LANGUAGE plpgsql;</programlisting> </para> </sect2> <sect2 id="plpgsql-declaration-type"> <title>Copying Types</title><synopsis><replaceable>variable</replaceable>%TYPE</synopsis> <para> <literal>%TYPE</literal> provides the data type of a variable or table column. You can use this to declare variables that will hold database values. For example, let's say you have a column named <literal>user_id</literal> in your <literal>users</literal> table. To declare a variable with the same data type as <literal>users.user_id</> you write:<programlisting>user_id users.user_id%TYPE;</programlisting> </para> <para> By using <literal>%TYPE</literal> you don't need to know the data type of the structure you are referencing, and most importantly, if the data type of the referenced item changes in the future (for instance: you change the type of <literal>user_id</> from <type>integer</type> to <type>real</type>), you may not need to change your function definition. </para> <para> <literal>%TYPE</literal> is particularly valuable in polymorphic functions, since the data types needed for internal variables may change from one call to the next. Appropriate variables can be created by applying <literal>%TYPE</literal> to the function's arguments or result placeholders. </para> </sect2> <sect2 id="plpgsql-declaration-rowtypes"> <title>Row Types</title><synopsis><replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;<replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;</synopsis> <para> A variable of a composite type is called a <firstterm>row</> variable (or <firstterm>row-type</> variable). Such a variable can hold a whole row of a <command>SELECT</> or <command>FOR</> query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example <literal>rowvar.field</literal>. </para> <para> A row variable can be declared to have the same type as the rows of an existing table or view, by using the <replaceable>table_name</replaceable><literal>%ROWTYPE</literal> notation; or it can be declared by giving a composite type's name. (Since every table has an associated composite type of the same name, it actually does not matter in <productname>PostgreSQL</> whether you write <literal>%ROWTYPE</literal> or not. But the form with <literal>%ROWTYPE</literal> is more portable.) </para> <para> Parameters to a function can be composite types (complete table rows). In that case, the corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can be selected from it, for example <literal>$1.user_id</literal>. </para> <para> Only the user-defined columns of a table row are accessible in a row-type variable, not the OID or other system columns (because the row could be from a view). The fields of the row type inherit the table's field size or precision for data types such as <type>char(<replaceable>n</>)</type>. </para> <para> Here is an example of using composite types:<programlisting>CREATE FUNCTION use_two_tables(tablename) RETURNS text AS 'DECLARE in_t ALIAS FOR $1; use_t table2name%ROWTYPE;BEGIN SELECT * INTO use_t FROM table2name WHERE ... ; RETURN in_t.f1 || use_t.f3 || in_t.f5 || use_t.f7;END;' LANGUAGE plpgsql;</programlisting> </para> </sect2> <sect2 id="plpgsql-declaration-records"> <title>Record Types</title><synopsis><replaceable>name</replaceable> RECORD;</synopsis> <para> Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a <command>SELECT</> or <command>FOR</> command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error. </para> <para> Note that <literal>RECORD</> is not a true data type, only a placeholder. One should also realize that when a <application>PL/pgSQL</application> function is declared to return type <type>record</>, this is not quite the same concept as a record variable, even though such a function may well use a record variable to hold its result. In both cases the actual row structure is unknown when the function is written, but for a function returning <type>record</> the actual structure is determined when the calling query is parsed, whereas a record variable can change its row structure on-the-fly. </para> </sect2> <sect2 id="plpgsql-declaration-renaming-vars"> <title><literal>RENAME</></title><synopsis>RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;</synopsis> <para> Using the <literal>RENAME</literal> declaration you can change the name of a variable, record or row. This is primarily useful if <literal>NEW</literal> or <literal>OLD</literal> should be
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -