我创建了自定义类型
CREATE TYPE address AS (city VARCHAR(90), street VARCHAR(90));
我需要将此类型转换为字符varying[]
。我收到错误
无法将customtype_address类型转换为字符变化[]
答案 0 :(得分:1)
您需要创建强制转换功能:
[local] @ test #= CREATE TYPE address AS (city VARCHAR(90), street VARCHAR(90));
CREATE TYPE
[local] @ test #= -- CREATE the cast function
CREATE OR REPLACE FUNCTION address2varchar_array (address address)
RETURNS VARCHAR[] AS $$
SELECT ARRAY[address.city, address.street]
$$ LANGUAGE SQL;
[local] @ test #= -- CREATE the cast
CREATE CAST (address AS VARCHAR[]) WITH FUNCTION address2varchar_array(address);
然后:
[local] @ test #= CREATE TEMP TABLE t (a address);
CREATE TABLE
[local] @ test #= INSERT INTO t VALUES (('paris', 'something'));
INSERT 0 1
[local] @ test #= SELECT a::VARCHAR[] FROM t;
┌───────────────────┐
│ a │
├───────────────────┤
│ {paris,something} │
└───────────────────┘
(1 row)
答案 1 :(得分:1)
CREATE TYPE address AS (city VARCHAR(90), street VARCHAR(90));
CREATE TABLE contact1 (adr address);
INSERT INTO contact1 VALUES (('cityone', 'addressone'));
创建一个如下所示的函数,将address
类型转换为varchar[]
create or replace function addresstovarchar(val address) returns
varchar[] as
$$
select string_to_array(trim(trim(val::text,'('),')'),',')::varchar[]
$$language sql
用法:
select addresstovarchar(adr) from contact1