DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.tables 
        WHERE table_schema = 'AKUZ' 
        AND table_name = 't_add_hospital_service'
    ) THEN

        CREATE TABLE AKUZ.T_ADD_HOSPITAL_SERVICE
        (
            "medicalrecordid" uuid NOT NULL,
            "ii" boolean NOT NULL
        );

        ALTER TABLE AKUZ.T_ADD_HOSPITAL_SERVICE 
        ADD CONSTRAINT PK_T_ADD_HOSPITAL_SERVICE
        PRIMARY KEY ("medicalrecordid");

        ALTER TABLE AKUZ.T_ADD_HOSPITAL_SERVICE 
        ADD CONSTRAINT FK_T_HOSPITAL_SERVICE_T_ADD_HOSPITAL_SERVICE_MedicalRecordID
        FOREIGN KEY("medicalrecordid") 
        REFERENCES AKUZ.T_HOSPITAL_SERVICE ("medicalrecordid");

        INSERT INTO AKUZ.T_ADD_HOSPITAL_SERVICE ("medicalrecordid", "ii")
        SELECT "medicalrecordid", false
        FROM AKUZ.T_MEDICAL_RECORD mr
        WHERE EXISTS (
            SELECT 1 FROM VCLib.T_ENTITIES e
            WHERE e."entname" = 'ADD_HOSPITAL_SERVICE' 
            AND e."schema" = 'AKUZ' 
            AND e."entityid" = mr."type_"
        );

    END IF;
END $$;