2016-03-29 56 views
0

爲了將新的用戶定義的ENUM類型的結果列表作爲可能的值使用,我獲取了所有內置和用戶定義的類型。從查詢結果中創建一個ENUM類型

SELECT pg_catalog.format_type(t.oid, NULL) into TYPES_NAMES 
FROM pg_catalog.pg_type t 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace 
WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM 
pg_catalog.pg_class c WHERE c.oid = t.typrelid)) 
AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid =  
t.typelem AND el.typarray = t.oid) 
AND pg_catalog.pg_type_is_visible(t.oid); 

如何使用所產生的類型列表作爲新ENUM類型可以有可能值。

CREATE TYPE my_enum AS ENUM (....); 

我使用PostgreSQL 9.5.0

感謝

回答

1

您可以通過在PLPGSQL值迭代,並將它們添加到您的枚舉有:

ALTER TYPE name ADD VALUE 'value'; 
+0

感謝您的回答。我可以通過遍歷這些值來完成。 – saloua

0

我可以用一個內嵌做命令通過迭代thx值到Dmitri的答案。

DO $$ 
DECLARE name text; 
BEGIN 
    -- create an empty type then add the possible values 
    EXECUTE 'CREATE TYPE data_types_enum AS ENUM()'; 
    FOR name IN 
    SELECT pg_catalog.format_type(t.oid, NULL) as TYPES_NAMES 
    FROM pg_catalog.pg_type t 
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace 
    WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM 
    pg_catalog.pg_class c WHERE c.oid = t.typrelid)) 
    AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = 
    t.typelem AND el.typarray = t.oid) 
    AND pg_catalog.pg_type_is_visible(t.oid) 
    LOOP 
    -- add the possible types 
    EXECUTE 'ALTER TYPE data_types_enum ADD VALUE ''' ||name|| ''''; 
    END LOOP; 
END $$;