将 SQL 结果传递给接受数组的 PostgreSQL 函数的语法错误
Syntax error passing SQL result to PostgreSQL function accepting array
我试图将 SQL 查询的结果传递给一个函数,但出现语法错误。
contacts=> SELECT count(*) FROM update_name(contact_ids := select array(select id from contact where name is NULL));
ERROR: syntax error at or near "select"
LINE 1: SELECT count(*) FROM update_name(contact_ids := select array...
subselect returns BIGINT,函数接受 BIGINT 数组。我验证了 运行 子选择并将结果转换为 BIGINT 数组是有效的。
切换到 positional notation did not make a difference. Using an Array constructor 也没有任何改变。
根据直觉,我将参数包装在 parens:
SELECT count(*) FROM update_name(contact_ids := (select array(select id from contact where name is NULL)));
并且有效。我不明白为什么。 docs on expressions 声明函数调用中的参数是表达式。函数调用和 Array 构造函数都是表达式,所以至少使用 Array 构造函数应该有效。
为什么我需要 parens?必要性从何而来,即我怎么知道?
您使用的表达形式称为Scalar Subquery。手册说:
A scalar subquery is an ordinary SELECT query in parentheses that
returns exactly one row with one column ... The SELECT query is executed and
the single returned value is used in the surrounding value expression.
您的子查询 returns 单个值(恰好是一个数组,由另一个子查询的结果准备)。
作为基本的经验法则,子查询总是在括号中。
我试图将 SQL 查询的结果传递给一个函数,但出现语法错误。
contacts=> SELECT count(*) FROM update_name(contact_ids := select array(select id from contact where name is NULL));
ERROR: syntax error at or near "select"
LINE 1: SELECT count(*) FROM update_name(contact_ids := select array...
subselect returns BIGINT,函数接受 BIGINT 数组。我验证了 运行 子选择并将结果转换为 BIGINT 数组是有效的。
切换到 positional notation did not make a difference. Using an Array constructor 也没有任何改变。
根据直觉,我将参数包装在 parens:
SELECT count(*) FROM update_name(contact_ids := (select array(select id from contact where name is NULL)));
并且有效。我不明白为什么。 docs on expressions 声明函数调用中的参数是表达式。函数调用和 Array 构造函数都是表达式,所以至少使用 Array 构造函数应该有效。
为什么我需要 parens?必要性从何而来,即我怎么知道?
您使用的表达形式称为Scalar Subquery。手册说:
A scalar subquery is an ordinary SELECT query in parentheses that returns exactly one row with one column ... The SELECT query is executed and the single returned value is used in the surrounding value expression.
您的子查询 returns 单个值(恰好是一个数组,由另一个子查询的结果准备)。
作为基本的经验法则,子查询总是在括号中。