返回的列数与预期的列数不匹配 // 在 plpgsql 函数中返回串联行

问题描述 投票:0回答:1

我正在尝试创建查询:通过电话号码搜索人员的统计信息。 我开始在内部查询中使用

INNER JOIN
,现在我不明白我必须如何返回类型。 我尝试使用视图作为类型,但它们不能包含具有相同名称的属性。好吧,我把它削减到3。 但我仍然收到错误并且不明白这意味着什么:

ERROR:  structure of query does not match function result type
DETAIL:  Number of returned columns (3) does not match expected column count (2).
CONTEXT:  PL/pgSQL function get_fio_by_phone_number(bigint) line 3 at RETURN QUERY
SQL state: 42804

代码:

CREATE OR REPLACE VIEW persons_fios_and_telephons AS
    SELECT p.name, p.surname, pt.number
    FROM person p
    INNER JOIN persons_telefons pt on p.id = pt.person_id;
    

DROP FUNCTION get_fio_by_phone_number(bigint);

CREATE OR REPLACE FUNCTION get_fio_by_phone_number(user_phone BIGINT) RETURNS SETOF persons_and_telephons
AS $$
BEGIN
  RETURN QUERY
    SELECT *
    FROM persons_fios_and_telephons pat
    WHERE pat.number = get_fio_by_phone_number.user_phone;
  
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      RAISE EXCEPTION 'There is no person with number "%".', user_phone;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM get_fio_by_phone_number(89998887766)

有没有办法让函数无需粗略的属性枚举?谢谢!

postgresql plpgsql
1个回答
0
投票

我创建了

person
表,然后在其中插入了 2 行,如下所示:

CREATE TABLE person (
  id INTEGER,
  name VARCHAR(20),
  age INTEGER
);

INSERT INTO person (id, name, age) 
VALUES (1, 'John', 27), (2, 'David', 32);

然后,我创建了

my_func()
,它返回
person
表,如下所示:

CREATE FUNCTION my_func() RETURNS TABLE(id INTEGER, name VARCHAR, age INTEGER)
AS $$
BEGIN
  RETURN QUERY SELECT person.id, person.name FROM person;
END;        -- ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
$$ LANGUAGE plpgsql;

最后,调用

my_func()
得到了同样的错误,如下所示:

postgres=# SELECT my_func();
ERROR:  structure of query does not match function result type
DETAIL:  Number of returned columns (2) does not match expected column count (3).
CONTEXT:  SQL statement "SELECT person.id, person.name FROM person"
PL/pgSQL function my_func() line 3 at RETURN QUERY

所以,我添加了

person.age
,如下所示:

CREATE FUNCTION my_func() RETURNS TABLE(id INTEGER, name VARCHAR, age INTEGER)
AS $$
BEGIN
  RETURN QUERY SELECT person.id, person.name, person.age FROM person;
END;                                       -- ↑↑↑↑↑↑↑↑↑↑
$$ LANGUAGE plpgsql;

最后,我可以毫无错误地调用

my_func()
,如下所示。在
person
.
id
中省略表名
name
age
会得到 错误,并且在
SELECT 语句
中省略 FROM 子句会得到 错误:

postgres=# SELECT my_func();
INSERT 0 1
postgres=# SELECT * FROM person;
   my_func
--------------
 (1,John,27)
 (2,David,32)
(2 rows)
© www.soinside.com 2019 - 2024. All rights reserved.