# 43.3.声明

43.3.1. 声明函数参数

43.3.2.别名

43.3.3. 复制类型

43.3.4. 行类型

43.3.5. 记录类型

43.3.6. PL/pgSQL变量的排序

块中使用的所有变量必须在块的声明部分声明。(唯一的例外是对于在整数值范围内迭代的循环会自动声明为整数变量,同样,也会声明为对于在游标结果上迭代的循环将自动声明为记录变量。)

PL/pgSQL变量可以有任何SQL数据类型,例如整数,瓦尔查尔烧焦.

以下是一些变量声明的示例:

user_id integer;
quantity numeric(5);
url varchar;
myrow tablename%ROWTYPE;
myfield tablename.columnname%TYPE;
arow RECORD;

变量声明的一般语法为:

name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | := | = } expression ];

这个违约子句(如果给定)指定输入块时分配给变量的初始值。如果违约子句,则变量被初始化为SQL空值。这个常数选项可防止在初始化后将变量指定给,以便其值在块的持续时间内保持不变。这个整理选项指定用于变量的排序规则(请参见第43.3.6节).如果非空如果指定,则赋值为空会导致运行时错误。所有变量声明为非空必须指定非空的默认值。同等的(=)可以用来代替PL/SQL兼容:=.

每次输入块时(而不是每次函数调用一次),都会计算变量的默认值并将其分配给变量。例如,分配现在()类型的变量时间戳使变量具有当前函数调用的时间,而不是函数预编译的时间。

例如:

quantity integer DEFAULT 32;
url varchar := 'http://mysite.com';
user_id CONSTANT integer := 10;

# 43.3.1.声明函数参数

传递给函数的参数用标识符命名$1, $2,等等。也可以为其声明别名$*n*增加可读性的参数名称。然后可以使用别名或数字标识符来引用参数值。

创建别名有两种方法。首选的方法是在创建函数命令,例如:

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

另一种方法是使用声明语法显式声明别名

name ALIAS FOR $n;

此样式中的相同示例如下所示:

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 using v_string and index here
END;
$$ LANGUAGE plpgsql;

CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
$$ LANGUAGE plpgsql;

使用输出参数声明PL/pgSQL函数时,会给出输出参数$*n*名称和可选别名的方式与普通输入参数相同。输出参数实际上是一个以NULL开头的变量;在功能执行期间,应将其分配给。参数的最终值是返回的值。例如,销售税的例子也可以这样做:

CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
BEGIN
    tax := subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

注意,我们忽略了回归真实-我们本可以把它包括在内,但它是多余的。

调用函数出来参数,省略函数调用中的输出参数:

SELECT sales_tax(100.00);

当返回多个值时,输出参数最有用。一个简单的例子是:

CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
BEGIN
    sum := x + y;
    prod := x * y;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM sum_n_product(2, 4);
 sum | prod
### 43.3.2. `ALIAS`

新名称旧名称的别名;

 The `ALIAS` syntax is more general than is suggested in the previous section: you can declare an alias for any variable, not just function parameters. The main practical use for this is to assign a different name for variables with predetermined names, such as `NEW` or `OLD` within a trigger function.

 Examples:

为old声明先前的别名;更新了新的别名;

 Since `ALIAS` creates two different ways to name the same object, unrestricted use can be confusing. It's best to use it only for the purpose of overriding predetermined names.

### 43.3.3. Copying Types

变量%TYPE

`%TYPE` 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 `user_id` in your `users` table. To declare a variable with the same data type as `users.user_id` you write:

用户id用户。用户id%类型;

 By using `%TYPE` 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 `user_id` from `integer` to `real`), you might not need to change your function definition.

`%TYPE` is particularly valuable in polymorphic functions, since the data types needed for internal variables can change from one call to the next. Appropriate variables can be created by applying `%TYPE` to the function's arguments or result placeholders.

### 43.3.4. Row Types

名称表\u名称%ROWTYPE;名称组合类型名称;

 A variable of a composite type is called a *row* variable (or *row-type* variable). Such a variable can hold a whole row of a `SELECT` or `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 `rowvar.field`.

 A row variable can be declared to have the same type as the rows of an existing table or view, by using the *`table_name`*`%ROWTYPE` 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 PostgreSQL whether you write `%ROWTYPE` or not. But the form with `%ROWTYPE` is more portable.)

 Parameters to a function can be composite types (complete table rows). In that case, the corresponding identifier `$*`n`*` will be a row variable, and fields can be selected from it, for example `$1.user_id`.

 Here is an example of using composite types. `table1` and `table2` are existing tables having at least the mentioned fields:

创建函数merge_fields(t_row table1)将文本返回为$$DECLARE t2_row table2%ROWTYPE;从表2开始选择*进入t2_行,其中;返回t_row。f1 | | t2 |排。f3 | | t|路。f5 | | t2 |排。f7;完$$语言plpgsql;

从表1 t中选择合并字段(t*),其中;

### 43.3.5. Record Types

姓名记录;

 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 `SELECT` or `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.

 Note that `RECORD` is not a true data type, only a placeholder. One should also realize that when a PL/pgSQL function is declared to return type `record`, this is not quite the same concept as a record variable, even though such a function might 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 `record` the actual structure is determined when the calling query is parsed, whereas a record variable can change its row structure on-the-fly.

### 43.3.6. Collation of PL/pgSQL Variables

[]()

 When a PL/pgSQL 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 [Section 24.2](collation.html). 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, consider

CREATE FUNCTION less_than(a text,b text)返回布尔值作为$$BEGIN返回a<b;完$$语言plpgsql;

从表1中选择小于(文本字段1,文本字段2);从表1中选择小于(文本字段1,文本字段2校对“C”);

 The first use of `less_than` will use the common collation of `text_field_1` and `text_field_2` for the comparison, while the second use will use `C` collation.

 Furthermore, the identified collation is also assumed as the collation of any local variables that are of collatable types. Thus this function would not work any differently if it were written as

CREATE FUNCTION less_than(a text,b text)返回布尔值为$$DECLARE local_a text:=a;本地文本:=b;开始返回本地_a<local_b;完$$语言plpgsql;

 If there are no parameters of collatable data types, or no common collation can be identified for them, then parameters and local variables use the default collation of their data type (which is usually the database's default collation, but could be different for variables of domain types).

 A local variable of a collatable data type can have a different collation associated with it by including the `COLLATE` option in its declaration, for example

声明本地的一个文本校对“en_US”;

 This option overrides the collation that would otherwise be given to the variable according to the rules above.

 Also, of course explicit `COLLATE` clauses can be written inside a function if it is desired to force a particular collation to be used in a particular operation. For example,

CREATE FUNCTION less_than_c(a text,b text)返回布尔值作为$$BEGIN返回a<b COLLATE“c”;完$$语言plpgsql;

 This overrides the collations associated with the table columns, parameters, or local variables used in the expression, just as would happen in a plain SQL command.