我正在Azure上运行PostgreSQL 10.5。我想创建一个存储过程来返回一组行,所以我从安装脚本中复制所选数据的类型:
DROP TYPE t CASCADE;
CREATE TYPE t as (region varchar(24), county varchar(50), year int, value int);
DROP FUNCTION geo();
CREATE FUNCTION geo()
returns setof t language sql as $$
SELECT
region.name, county.name, tbl.year, tbl.value
FROM tbl
LEFT JOIN county ON tbl.lau1 = county.lau1
LEFT JOIN region ON county.regionid = region.regionid
$$;
我得到了错误:
ERROR: return type mismatch in function declared to return t
DETAIL: Final statement returns character instead of character varying at column 1.
CONTEXT: SQL function "geo"
但是,类型与创建region
和county
表中的类型相同(并且我还包括了tbl
的代码):
CREATE TABLE county (
LAU1 CHAR(9),
NAME VARCHAR(50) NOT NULL,
REGIONID INT NOT NULL,
PRIMARY KEY(LAU1)
);
CREATE TABLE region (
REGIONID SMALLINT,
NAME VARCHAR(24) NOT NULL,
PRIMARY KEY(REGIONID)
);
CREATE TABLE tbl (
LAU1 CHAR(9),
YEAR INT,
VALUE INT,
PRIMARY KEY(LAU1, YEAR)
);
三个表的示例:
=> select * from county limit 2;
lau1 | name | regionid
-----------+-----------+----------
E06000015 | Derby | 4
E06000016 | Leicester | 4
(2 rows)
=> select * from region limit 2;
regionid | name
----------+--------------------------
1 | North East
2 | North West
(2 rows)
=> select * from tbl limit 2;
lau1 | year | value
-----------+------+-------
E06000047 | 1997 | 3241
E06000005 | 1997 | 656
(2 rows)
我想在返回的值中保留与varchar
的原始类型相同的类型。但是作为实验,如果我将元组的第一类型从varchar
更改为char
:
CREATE TYPE t as (region char(24), county varchar(50), year int, value int);
和其余代码一样,尽管第二列保留了varchar
,它仍然可以工作!
select * from geo();
region | county | year | value
--------------------------+------------+------+-------
North East | Hartlepool | 1997 | 625
(1 row)
怎么来?