Check if a user-defined type already exists in PostgreSQL

后端 未结 10 1595
离开以前
离开以前 2020-12-29 01:43

Say I have created some user-defined types in the DB,

i.e. CREATE TYPE abc ...

Is it then possible to determine if the user-defined type exists

10条回答
  •  半阙折子戏
    2020-12-29 02:45

    -- All of this to create a type if it does not exist
    CREATE OR REPLACE FUNCTION create_abc_type() RETURNS integer AS $$
    DECLARE v_exists INTEGER;
    
    BEGIN
        SELECT into v_exists (SELECT 1 FROM pg_type WHERE typname = 'abc');
        IF v_exists IS NULL THEN
            CREATE TYPE abc AS ENUM ('height', 'weight', 'distance');
        END IF;
        RETURN v_exists;
    END;
    $$ LANGUAGE plpgsql;
    
    -- Call the function you just created
    SELECT create_abc_type();
    
    -- Remove the function you just created
    DROP function create_abc_type();
    -----------------------------------
    

提交回复
热议问题