DROP TABLE IF EXISTS RDS.T_NEWBORN_PRINT_DOCUMENTS;
DROP TABLE IF EXISTS RDS.T_OBSTETRICS_PRINT_DOCUMENTS;
DROP TABLE IF EXISTS RDS.T_PERINATAL_CARD;
DROP TABLE IF EXISTS RDS.T_MOTHERHOOD_EVENT;
DROP TABLE IF EXISTS RDS.T_DELIVERY_AND_POSTPARTUM_PERIOD;
DROP TABLE IF EXISTS RDS.T_NEWBORN_DEVELOPMENT_HISTORY;
DROP TABLE IF EXISTS RDS.T_PREGNANT_HOSPITALIZATION;
DROP TABLE IF EXISTS RDS.T_MEDICAL_RECORDS_PRINT;

CREATE TABLE temp_entity AS
SELECT EntityID
FROM VCLib.T_ENTITIES e
WHERE e.EntName IN (
    'NEWBORN_PRINT_DOCUMENTS',
    'OBSTETRICS_PRINT_DOCUMENTS',
    'PERINATAL_CARD',
    'MOTHERHOOD_EVENT',
    'DELIVERY_AND_POSTPARTUM_PERIOD',
    'NEWBORN_DEVELOPMENT_HISTORY',
    'PREGNANT_HOSPITALIZATION',
    'MEDICAL_RECORDS_PRINT'
);

DELETE FROM VCLib.T_USER_COLUMNS col
USING VCLib.T_USER_CONTEXTS ctx, temp_entity e
WHERE col.UserContextID = ctx.UserContextID
  AND ctx.EntityID = e.EntityID;

DELETE FROM VCLib.T_USER_CONTEXTS ctx
USING temp_entity e
WHERE ctx.EntityID = e.EntityID;

DELETE FROM VCLib.T_DELETED_OBJECT del
USING temp_entity e
WHERE del.Entities = e.EntityID;

DELETE FROM VCLib.T_TEMPLATE_FIELD_VALUE fv
USING VCLib.T_TEMPLATE_FIELD fld, temp_entity e
WHERE fv.TemplateField = fld.TemplateFieldID
  AND fld.Entity = e.EntityID;

DELETE FROM VCLib.T_TEMPLATE_FIELD fld
USING temp_entity e
WHERE fld.Entity = e.EntityID;

DELETE FROM VCLib.T_Report rep
USING temp_entity e
WHERE rep.EntityID = e.EntityID;

DELETE FROM VCLib.T_USER_SEARCHES us
USING temp_entity e
WHERE us.EntityID = e.EntityID;

DELETE FROM VCLib.T_FILE_CONTENT fc
USING VCLib.T_FILE f, temp_entity e
WHERE f.FileID = fc.FileContentID
  AND f.Type_ = e.EntityID;

DELETE FROM VCLib.T_FILE f
USING temp_entity e
WHERE f.Type_ = e.EntityID;

DELETE FROM VCLib.T_ENTITIES_ATTRIBUTES ea
USING temp_entity e
WHERE ea.EntityID = e.EntityID;

DELETE FROM VCLib.T_ENTITIES ent
USING temp_entity e
WHERE ent.EntityID = e.EntityID;

DROP TABLE temp_entity;
