gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

395 行
22KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>42.3. Declarations</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="plpgsql-structure.html" title="42.2. Structure of PL/pgSQL" /><link rel="next" href="plpgsql-expressions.html" title="42.4. Expressions" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">42.3. Declarations</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plpgsql-structure.html" title="42.2. Structure of PL/pgSQL">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plpgsql.html" title="Chapter 42. PL/pgSQL - SQL Procedural Language">Up</a></td><th width="60%" align="center">Chapter 42. <span xmlns="http://www.w3.org/1999/xhtml" class="application">PL/pgSQL</span> - <acronym xmlns="http://www.w3.org/1999/xhtml" class="acronym">SQL</acronym> Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plpgsql-expressions.html" title="42.4. Expressions">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="PLPGSQL-DECLARATIONS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">42.3. Declarations</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-PARAMETERS">42.3.1. Declaring Function Parameters</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-ALIAS">42.3.2. <code class="literal">ALIAS</code></a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-TYPE">42.3.3. Copying Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES">42.3.4. Row Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-RECORDS">42.3.5. Record Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-COLLATION">42.3.6. Collation of <span class="application">PL/pgSQL</span> Variables</a></span></dt></dl></div><p>
  3. All variables used in a block must be declared in the
  4. declarations section of the block.
  5. (The only exceptions are that the loop variable of a <code class="literal">FOR</code> loop
  6. iterating over a range of integer values is automatically declared as an
  7. integer variable, and likewise the loop variable of a <code class="literal">FOR</code> loop
  8. iterating over a cursor's result is automatically declared as a
  9. record variable.)
  10. </p><p>
  11. <span class="application">PL/pgSQL</span> variables can have any SQL data type, such as
  12. <code class="type">integer</code>, <code class="type">varchar</code>, and
  13. <code class="type">char</code>.
  14. </p><p>
  15. Here are some examples of variable declarations:
  16. </p><pre class="programlisting">
  17. user_id integer;
  18. quantity numeric(5);
  19. url varchar;
  20. myrow tablename%ROWTYPE;
  21. myfield tablename.columnname%TYPE;
  22. arow RECORD;
  23. </pre><p>
  24. </p><p>
  25. The general syntax of a variable declaration is:
  26. </p><pre class="synopsis">
  27. <em class="replaceable"><code>name</code></em> [<span class="optional"> CONSTANT </span>] <em class="replaceable"><code>type</code></em> [<span class="optional"> COLLATE <em class="replaceable"><code>collation_name</code></em> </span>] [<span class="optional"> NOT NULL </span>] [<span class="optional"> { DEFAULT | := | = } <em class="replaceable"><code>expression</code></em> </span>];
  28. </pre><p>
  29. The <code class="literal">DEFAULT</code> clause, if given, specifies the initial value assigned
  30. to the variable when the block is entered. If the <code class="literal">DEFAULT</code> clause
  31. is not given then the variable is initialized to the
  32. <acronym class="acronym">SQL</acronym> null value.
  33. The <code class="literal">CONSTANT</code> option prevents the variable from being
  34. assigned to after initialization, so that its value will remain constant
  35. for the duration of the block.
  36. The <code class="literal">COLLATE</code> option specifies a collation to use for the
  37. variable (see <a class="xref" href="plpgsql-declarations.html#PLPGSQL-DECLARATION-COLLATION" title="42.3.6. Collation of PL/pgSQL Variables">Section 42.3.6</a>).
  38. If <code class="literal">NOT NULL</code>
  39. is specified, an assignment of a null value results in a run-time
  40. error. All variables declared as <code class="literal">NOT NULL</code>
  41. must have a nonnull default value specified.
  42. Equal (<code class="literal">=</code>) can be used instead of PL/SQL-compliant
  43. <code class="literal">:=</code>.
  44. </p><p>
  45. A variable's default value is evaluated and assigned to the variable
  46. each time the block is entered (not just once per function call).
  47. So, for example, assigning <code class="literal">now()</code> to a variable of type
  48. <code class="type">timestamp</code> causes the variable to have the
  49. time of the current function call, not the time when the function was
  50. precompiled.
  51. </p><p>
  52. Examples:
  53. </p><pre class="programlisting">
  54. quantity integer DEFAULT 32;
  55. url varchar := 'http://mysite.com';
  56. user_id CONSTANT integer := 10;
  57. </pre><p>
  58. </p><div class="sect2" id="PLPGSQL-DECLARATION-PARAMETERS"><div class="titlepage"><div><div><h3 class="title">42.3.1. Declaring Function Parameters</h3></div></div></div><p>
  59. Parameters passed to functions are named with the identifiers
  60. <code class="literal">$1</code>, <code class="literal">$2</code>,
  61. etc. Optionally, aliases can be declared for
  62. <code class="literal">$<em class="replaceable"><code>n</code></em></code>
  63. parameter names for increased readability. Either the alias or the
  64. numeric identifier can then be used to refer to the parameter value.
  65. </p><p>
  66. There are two ways to create an alias. The preferred way is to give a
  67. name to the parameter in the <code class="command">CREATE FUNCTION</code> command,
  68. for example:
  69. </p><pre class="programlisting">
  70. CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
  71. BEGIN
  72. RETURN subtotal * 0.06;
  73. END;
  74. $$ LANGUAGE plpgsql;
  75. </pre><p>
  76. The other way is to explicitly declare an alias, using the
  77. declaration syntax
  78. </p><pre class="synopsis">
  79. <em class="replaceable"><code>name</code></em> ALIAS FOR $<em class="replaceable"><code>n</code></em>;
  80. </pre><p>
  81. The same example in this style looks like:
  82. </p><pre class="programlisting">
  83. CREATE FUNCTION sales_tax(real) RETURNS real AS $$
  84. DECLARE
  85. subtotal ALIAS FOR $1;
  86. BEGIN
  87. RETURN subtotal * 0.06;
  88. END;
  89. $$ LANGUAGE plpgsql;
  90. </pre><p>
  91. </p><div class="note"><h3 class="title">Note</h3><p>
  92. These two examples are not perfectly equivalent. In the first case,
  93. <code class="literal">subtotal</code> could be referenced as
  94. <code class="literal">sales_tax.subtotal</code>, but in the second case it could not.
  95. (Had we attached a label to the inner block, <code class="literal">subtotal</code> could
  96. be qualified with that label, instead.)
  97. </p></div><p>
  98. Some more examples:
  99. </p><pre class="programlisting">
  100. CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
  101. DECLARE
  102. v_string ALIAS FOR $1;
  103. index ALIAS FOR $2;
  104. BEGIN
  105. -- some computations using v_string and index here
  106. END;
  107. $$ LANGUAGE plpgsql;
  108. CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
  109. BEGIN
  110. RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
  111. END;
  112. $$ LANGUAGE plpgsql;
  113. </pre><p>
  114. </p><p>
  115. When a <span class="application">PL/pgSQL</span> function is declared
  116. with output parameters, the output parameters are given
  117. <code class="literal">$<em class="replaceable"><code>n</code></em></code> names and optional
  118. aliases in just the same way as the normal input parameters. An
  119. output parameter is effectively a variable that starts out NULL;
  120. it should be assigned to during the execution of the function.
  121. The final value of the parameter is what is returned. For instance,
  122. the sales-tax example could also be done this way:
  123. </p><pre class="programlisting">
  124. CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
  125. BEGIN
  126. tax := subtotal * 0.06;
  127. END;
  128. $$ LANGUAGE plpgsql;
  129. </pre><p>
  130. Notice that we omitted <code class="literal">RETURNS real</code> — we could have
  131. included it, but it would be redundant.
  132. </p><p>
  133. Output parameters are most useful when returning multiple values.
  134. A trivial example is:
  135. </p><pre class="programlisting">
  136. CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
  137. BEGIN
  138. sum := x + y;
  139. prod := x * y;
  140. END;
  141. $$ LANGUAGE plpgsql;
  142. </pre><p>
  143. As discussed in <a class="xref" href="xfunc-sql.html#XFUNC-OUTPUT-PARAMETERS" title="37.5.4. SQL Functions with Output Parameters">Section 37.5.4</a>, this
  144. effectively creates an anonymous record type for the function's
  145. results. If a <code class="literal">RETURNS</code> clause is given, it must say
  146. <code class="literal">RETURNS record</code>.
  147. </p><p>
  148. Another way to declare a <span class="application">PL/pgSQL</span> function
  149. is with <code class="literal">RETURNS TABLE</code>, for example:
  150. </p><pre class="programlisting">
  151. CREATE FUNCTION extended_sales(p_itemno int)
  152. RETURNS TABLE(quantity int, total numeric) AS $$
  153. BEGIN
  154. RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
  155. WHERE s.itemno = p_itemno;
  156. END;
  157. $$ LANGUAGE plpgsql;
  158. </pre><p>
  159. This is exactly equivalent to declaring one or more <code class="literal">OUT</code>
  160. parameters and specifying <code class="literal">RETURNS SETOF
  161. <em class="replaceable"><code>sometype</code></em></code>.
  162. </p><p>
  163. When the return type of a <span class="application">PL/pgSQL</span>
  164. function is declared as a polymorphic type (<code class="type">anyelement</code>,
  165. <code class="type">anyarray</code>, <code class="type">anynonarray</code>, <code class="type">anyenum</code>,
  166. or <code class="type">anyrange</code>), a special parameter <code class="literal">$0</code>
  167. is created. Its data type is the actual return type of the function,
  168. as deduced from the actual input types (see <a class="xref" href="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" title="37.2.5. Polymorphic Types">Section 37.2.5</a>).
  169. This allows the function to access its actual return type
  170. as shown in <a class="xref" href="plpgsql-declarations.html#PLPGSQL-DECLARATION-TYPE" title="42.3.3. Copying Types">Section 42.3.3</a>.
  171. <code class="literal">$0</code> is initialized to null and can be modified by
  172. the function, so it can be used to hold the return value if desired,
  173. though that is not required. <code class="literal">$0</code> can also be
  174. given an alias. For example, this function works on any data type
  175. that has a <code class="literal">+</code> operator:
  176. </p><pre class="programlisting">
  177. CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
  178. RETURNS anyelement AS $$
  179. DECLARE
  180. result ALIAS FOR $0;
  181. BEGIN
  182. result := v1 + v2 + v3;
  183. RETURN result;
  184. END;
  185. $$ LANGUAGE plpgsql;
  186. </pre><p>
  187. </p><p>
  188. The same effect can be obtained by declaring one or more output parameters as
  189. polymorphic types. In this case the
  190. special <code class="literal">$0</code> parameter is not used; the output
  191. parameters themselves serve the same purpose. For example:
  192. </p><pre class="programlisting">
  193. CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
  194. OUT sum anyelement)
  195. AS $$
  196. BEGIN
  197. sum := v1 + v2 + v3;
  198. END;
  199. $$ LANGUAGE plpgsql;
  200. </pre><p>
  201. </p></div><div class="sect2" id="PLPGSQL-DECLARATION-ALIAS"><div class="titlepage"><div><div><h3 class="title">42.3.2. <code class="literal">ALIAS</code></h3></div></div></div><pre class="synopsis">
  202. <em class="replaceable"><code>newname</code></em> ALIAS FOR <em class="replaceable"><code>oldname</code></em>;
  203. </pre><p>
  204. The <code class="literal">ALIAS</code> syntax is more general than is suggested in the
  205. previous section: you can declare an alias for any variable, not just
  206. function parameters. The main practical use for this is to assign
  207. a different name for variables with predetermined names, such as
  208. <code class="varname">NEW</code> or <code class="varname">OLD</code> within
  209. a trigger function.
  210. </p><p>
  211. Examples:
  212. </p><pre class="programlisting">
  213. DECLARE
  214. prior ALIAS FOR old;
  215. updated ALIAS FOR new;
  216. </pre><p>
  217. </p><p>
  218. Since <code class="literal">ALIAS</code> creates two different ways to name the same
  219. object, unrestricted use can be confusing. It's best to use it only
  220. for the purpose of overriding predetermined names.
  221. </p></div><div class="sect2" id="PLPGSQL-DECLARATION-TYPE"><div class="titlepage"><div><div><h3 class="title">42.3.3. Copying Types</h3></div></div></div><pre class="synopsis">
  222. <em class="replaceable"><code>variable</code></em>%TYPE
  223. </pre><p>
  224. <code class="literal">%TYPE</code> provides the data type of a variable or
  225. table column. You can use this to declare variables that will hold
  226. database values. For example, let's say you have a column named
  227. <code class="literal">user_id</code> in your <code class="literal">users</code>
  228. table. To declare a variable with the same data type as
  229. <code class="literal">users.user_id</code> you write:
  230. </p><pre class="programlisting">
  231. user_id users.user_id%TYPE;
  232. </pre><p>
  233. </p><p>
  234. By using <code class="literal">%TYPE</code> you don't need to know the data
  235. type of the structure you are referencing, and most importantly,
  236. if the data type of the referenced item changes in the future (for
  237. instance: you change the type of <code class="literal">user_id</code>
  238. from <code class="type">integer</code> to <code class="type">real</code>), you might not need
  239. to change your function definition.
  240. </p><p>
  241. <code class="literal">%TYPE</code> is particularly valuable in polymorphic
  242. functions, since the data types needed for internal variables can
  243. change from one call to the next. Appropriate variables can be
  244. created by applying <code class="literal">%TYPE</code> to the function's
  245. arguments or result placeholders.
  246. </p></div><div class="sect2" id="PLPGSQL-DECLARATION-ROWTYPES"><div class="titlepage"><div><div><h3 class="title">42.3.4. Row Types</h3></div></div></div><pre class="synopsis">
  247. <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>table_name</code></em><code class="literal">%ROWTYPE</code>;
  248. <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>composite_type_name</code></em>;
  249. </pre><p>
  250. A variable of a composite type is called a <em class="firstterm">row</em>
  251. variable (or <em class="firstterm">row-type</em> variable). Such a variable
  252. can hold a whole row of a <code class="command">SELECT</code> or <code class="command">FOR</code>
  253. query result, so long as that query's column set matches the
  254. declared type of the variable.
  255. The individual fields of the row value
  256. are accessed using the usual dot notation, for example
  257. <code class="literal">rowvar.field</code>.
  258. </p><p>
  259. A row variable can be declared to have the same type as the rows of
  260. an existing table or view, by using the
  261. <em class="replaceable"><code>table_name</code></em><code class="literal">%ROWTYPE</code>
  262. notation; or it can be declared by giving a composite type's name.
  263. (Since every table has an associated composite type of the same name,
  264. it actually does not matter in <span class="productname">PostgreSQL</span> whether you
  265. write <code class="literal">%ROWTYPE</code> or not. But the form with
  266. <code class="literal">%ROWTYPE</code> is more portable.)
  267. </p><p>
  268. Parameters to a function can be
  269. composite types (complete table rows). In that case, the
  270. corresponding identifier <code class="literal">$<em class="replaceable"><code>n</code></em></code> will be a row variable, and fields can
  271. be selected from it, for example <code class="literal">$1.user_id</code>.
  272. </p><p>
  273. Here is an example of using composite types. <code class="structname">table1</code>
  274. and <code class="structname">table2</code> are existing tables having at least the
  275. mentioned fields:
  276. </p><pre class="programlisting">
  277. CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
  278. DECLARE
  279. t2_row table2%ROWTYPE;
  280. BEGIN
  281. SELECT * INTO t2_row FROM table2 WHERE ... ;
  282. RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
  283. END;
  284. $$ LANGUAGE plpgsql;
  285. SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
  286. </pre><p>
  287. </p></div><div class="sect2" id="PLPGSQL-DECLARATION-RECORDS"><div class="titlepage"><div><div><h3 class="title">42.3.5. Record Types</h3></div></div></div><pre class="synopsis">
  288. <em class="replaceable"><code>name</code></em> RECORD;
  289. </pre><p>
  290. Record variables are similar to row-type variables, but they have no
  291. predefined structure. They take on the actual row structure of the
  292. row they are assigned during a <code class="command">SELECT</code> or <code class="command">FOR</code> command. The substructure
  293. of a record variable can change each time it is assigned to.
  294. A consequence of this is that until a record variable is first assigned
  295. to, it has no substructure, and any attempt to access a
  296. field in it will draw a run-time error.
  297. </p><p>
  298. Note that <code class="literal">RECORD</code> is not a true data type, only a placeholder.
  299. One should also realize that when a <span class="application">PL/pgSQL</span>
  300. function is declared to return type <code class="type">record</code>, this is not quite the
  301. same concept as a record variable, even though such a function might
  302. use a record variable to hold its result. In both cases the actual row
  303. structure is unknown when the function is written, but for a function
  304. returning <code class="type">record</code> the actual structure is determined when the
  305. calling query is parsed, whereas a record variable can change its row
  306. structure on-the-fly.
  307. </p></div><div class="sect2" id="PLPGSQL-DECLARATION-COLLATION"><div class="titlepage"><div><div><h3 class="title">42.3.6. Collation of <span class="application">PL/pgSQL</span> Variables</h3></div></div></div><a id="id-1.8.8.5.13.2" class="indexterm"></a><p>
  308. When a <span class="application">PL/pgSQL</span> function has one or more
  309. parameters of collatable data types, a collation is identified for each
  310. function call depending on the collations assigned to the actual
  311. arguments, as described in <a class="xref" href="collation.html" title="23.2. Collation Support">Section 23.2</a>. If a collation is
  312. successfully identified (i.e., there are no conflicts of implicit
  313. collations among the arguments) then all the collatable parameters are
  314. treated as having that collation implicitly. This will affect the
  315. behavior of collation-sensitive operations within the function.
  316. For example, consider
  317. </p><pre class="programlisting">
  318. CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
  319. BEGIN
  320. RETURN a &lt; b;
  321. END;
  322. $$ LANGUAGE plpgsql;
  323. SELECT less_than(text_field_1, text_field_2) FROM table1;
  324. SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
  325. </pre><p>
  326. The first use of <code class="function">less_than</code> will use the common collation
  327. of <code class="structfield">text_field_1</code> and <code class="structfield">text_field_2</code> for
  328. the comparison, while the second use will use <code class="literal">C</code> collation.
  329. </p><p>
  330. Furthermore, the identified collation is also assumed as the collation of
  331. any local variables that are of collatable types. Thus this function
  332. would not work any differently if it were written as
  333. </p><pre class="programlisting">
  334. CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
  335. DECLARE
  336. local_a text := a;
  337. local_b text := b;
  338. BEGIN
  339. RETURN local_a &lt; local_b;
  340. END;
  341. $$ LANGUAGE plpgsql;
  342. </pre><p>
  343. </p><p>
  344. If there are no parameters of collatable data types, or no common
  345. collation can be identified for them, then parameters and local variables
  346. use the default collation of their data type (which is usually the
  347. database's default collation, but could be different for variables of
  348. domain types).
  349. </p><p>
  350. A local variable of a collatable data type can have a different collation
  351. associated with it by including the <code class="literal">COLLATE</code> option in its
  352. declaration, for example
  353. </p><pre class="programlisting">
  354. DECLARE
  355. local_a text COLLATE "en_US";
  356. </pre><p>
  357. This option overrides the collation that would otherwise be
  358. given to the variable according to the rules above.
  359. </p><p>
  360. Also, of course explicit <code class="literal">COLLATE</code> clauses can be written inside
  361. a function if it is desired to force a particular collation to be used in
  362. a particular operation. For example,
  363. </p><pre class="programlisting">
  364. CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
  365. BEGIN
  366. RETURN a &lt; b COLLATE "C";
  367. END;
  368. $$ LANGUAGE plpgsql;
  369. </pre><p>
  370. This overrides the collations associated with the table columns,
  371. parameters, or local variables used in the expression, just as would
  372. happen in a plain SQL command.
  373. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plpgsql-structure.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plpgsql.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plpgsql-expressions.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">42.2. Structure of <span class="application">PL/pgSQL</span> </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 42.4. Expressions</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1