我将获取所有内置和用户定义的类型,以便将结果类型列表用作新用户定义的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
由于
答案 0 :(得分:1)
您可以迭代plpgsql中的值并使用以下命令将它们添加到枚举中:
ALTER TYPE name ADD VALUE 'value';
答案 1 :(得分: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 $$;