postgresql - 被遗忘的赋值运算符 "="和常见的 ":="

标签 postgresql plpgsql assignment-operator colon-equals

PL/pgSQL 的文档说,变量的声明和赋值是用 := 完成的。 但是一个简单、更短且更现代 (见脚注) = 似乎按预期工作:

    CREATE OR REPLACE FUNCTION foo() RETURNS int AS $$
    DECLARE
      i int;
    BEGIN
      i = 0;  
      WHILE NOT i = 25 LOOP
          i = i + 1;
          i = i * i;
      END LOOP;
      RETURN i;
    END;
    $$ LANGUAGE plpgsql;

    > SELECT foo();
    25

请注意,Pl/pgSQL 可以清楚地区分分配和比较,如行所示

      WHILE NOT i = 25 LOOP

所以,问题是:

  • 我没有在文档中找到提到和/或解释这一点的部分吗?
  • 使用 = 而不是 := 是否有任何已知的后果?

编辑/脚注:

请像在 A Brief, Incomplete, and Mostly Wrong History of Programming Languages 中一样眨眨眼,接受“更现代”的部分:

1970 - Niklaus Wirth creates Pascal, a procedural language. Critics immediately denounce Pascal because it uses "x := x + y" syntax instead of the more familiar C-like "x = x + y". This criticism happens in spite of the fact that C has not yet been invented.

1972 - Dennis Ritchie invents a powerful gun that shoots both forward and backward simultaneously. Not satisfied with the number of deaths and permanent maimings from that invention he invents C and Unix.

最佳答案

在PL/PgSQL解析器中,赋值运算符定义为

assign_operator : '='
                | COLON_EQUALS
                ;

这是一项遗留功能,自 1998 年引入以来一直存在于源代码中 - 正如我们在 PostgreSQL Git repo 中看到的那样.

从版本 9.4 开始,它是 oficially documented .

在 pgsql 用户列表中提出了这种特质 - 对于同一事物有两个运算符 - 一些人要求将其删除,但它仍然保留在核心中,因为公平的遗留代码语料库依赖于它。

查看此 message from Tom Lane (core Pg developer) .

所以,直接回答你的问题:

Didn't I find some section in the docs which mention and/or explains this?

您没有找到它,因为它未记录在案,从 9.4 版开始已修复。

Are there any known consequences using = instead of :=.

使用 = 没有副作用,但您应该使用 := 进行赋值以使您的代码更具可读性,并且(作为副作用)更兼容使用 PL/SQL。

更新:在极少数情况下可能会产生副作用(参见 Erwin 的回答)


更新:由于 Daniel、Sandy 和其他人的输入,答案已更新。

关于postgresql - 被遗忘的赋值运算符 "="和常见的 ":=",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462322/

相关文章:

postgresql - PL/PgSQL : No function matches the given name and argument types. 您可能需要添加显式类型转换

sql - PostgreSQL 将字符串匹配到动态输入的字符串

postgresql - 用 2 列的多条记录构造一个字符串

postgresql - 将带有 CSV 的 varchar 参数转换为列值 postgres

c++ - C++ 中的赋值运算符重载

c++ - 如何为带有 ptr 的工厂类编写 cctor 和 op= 来抽象成员字段?

sql - Postgresql 向列添加规则以在选择时转换数据

node.js - ForEach 循环中的异步/等待 Node -Postgres 查询

postgresql - 通过 VPC 连接器连接 Google Cloud Platform 的计算引擎和应用引擎

c++ - 使用单个函数实现复制和 move 赋值