DO $$
DECLARE
  ent_id INTEGER;
BEGIN
  SELECT EntityID INTO ent_id
  FROM VCLib.T_ENTITIES
  WHERE EntName = 'EKB_HOSPITALIZATION_REFERRAL' AND "Schema" = 'AKUZ';

  DELETE FROM VCLib.T_USER_COLUMNS
	WHERE UserContextID IN (SELECT UserContextID
	FROM VCLib.T_USER_CONTEXTS
	WHERE EntityID = ent_id);

  DELETE FROM VCLib.T_USER_CONTEXTS WHERE EntityID = ent_id;

  DELETE FROM VCLib.T_ENTITIES_ATTRIBUTES WHERE EntityID = ent_id;

  DELETE FROM EHR.T_EHR_REFERENCE where Entities = ent_id;

  DELETE FROM VCLib.T_ENTITIES WHERE EntityID = ent_id;

  DROP TABLE AKUZ.T_EKB_HOSPITALIZATION_REFERRAL;
END $$;