DROP TABLE RDS.T_NEWBORN_PRINT_DOCUMENTS;
GO

DROP TABLE RDS.T_OBSTETRICS_PRINT_DOCUMENTS;
GO

DROP TABLE RDS.T_PERINATAL_CARD;
GO

DROP TABLE RDS.T_MOTHERHOOD_EVENT;
GO

DROP TABLE RDS.T_DELIVERY_AND_POSTPARTUM_PERIOD;
GO

DROP TABLE RDS.T_NEWBORN_DEVELOPMENT_HISTORY;
GO

DROP TABLE RDS.T_PREGNANT_HOSPITALIZATION;
GO

DROP TABLE RDS.T_MEDICAL_RECORDS_PRINT;
GO

SELECT EntityID
INTO #ENTITY
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'
);
GO

DELETE col
FROM VCLib.T_USER_COLUMNS col
JOIN VCLib.T_USER_CONTEXTS ctx ON col.UserContextID = ctx.UserContextID
JOIN #ENTITY e ON ctx.EntityID = e.EntityID;
GO

DELETE ctx
FROM VCLib.T_USER_CONTEXTS ctx
JOIN #ENTITY e ON ctx.EntityID = e.EntityID;
GO

DELETE del
FROM VCLib.T_DELETED_OBJECT del
JOIN #ENTITY e ON del.Entities = e.EntityID;
GO

DELETE fv
FROM VCLib.T_TEMPLATE_FIELD_VALUE fv
JOIN VCLib.T_TEMPLATE_FIELD fld ON fv.TemplateField = fld.TemplateFieldID
JOIN #ENTITY e ON fld.Entity = e.EntityID;
GO

DELETE fld
FROM VCLib.T_TEMPLATE_FIELD fld
JOIN #ENTITY e ON fld.Entity = e.EntityID;
GO

DELETE rep
FROM VCLib.T_Report rep
JOIN #ENTITY e ON rep.EntityID = e.EntityID;
GO

DELETE us
FROM VCLib.T_USER_SEARCHES us
JOIN #ENTITY e ON us.EntityID = e.EntityID;
GO

DELETE fc
FROM VCLib.T_FILE f
JOIN VCLib.T_FILE_CONTENT fc ON f.FileID = fc.FileContentID
JOIN #ENTITY e ON f.Type_ = e.EntityID;
GO

DELETE f
FROM VCLib.T_FILE f
JOIN #ENTITY e ON f.Type_ = e.EntityID;
GO

DELETE e
FROM VCLib.T_ENTITIES_ATTRIBUTES e
JOIN #ENTITY ee ON e.EntityID = ee.EntityID;
GO

DELETE e
FROM VCLib.T_ENTITIES e
JOIN #ENTITY ee ON e.EntityID = ee.EntityID;
GO

DROP TABLE #ENTITY;
GO
