DELETE FROM AKUZ.T_CDA_SEKCI_RESCONS_CHILDBIRTH;
DELETE FROM AKUZ.T_CDA_SVEDEN_MEDIC_RABOTN_CHILDBIRTH;

DROP TABLE AKUZ.T_CDA_SVEDEN_STRUKTURN_POD_CHILDBIRTH;

CREATE TEMP TABLE ENTITY
(
	EntityID uuid NULL
);

select EntityID 
INTO ENTITY
from VCLib.T_ENTITIES e
where e.EntName in (
'CDA_SVEDEN_STRUKTURN_POD_CHILDBIRTH'
)
and e.Schema = 'AKUZ';

Delete 
From VCLib.T_USER_COLUMNS col
	using VCLib.T_USER_CONTEXTS ctx, ENTITY e 
	where col.UserContextID = ctx.UserContextID and ctx.EntityID = e.EntityID;

Delete 
From VCLib.T_USER_CONTEXTS ctx
	using ENTITY e where  ctx.EntityID = e.EntityID;

delete 
from VCLib.T_DELETED_OBJECT del
	using ENTITY e where  del.Entities = e.EntityID;

delete 
From VCLib.T_TEMPLATE_FIELD_VALUE fv
using VCLib.T_TEMPLATE_FIELD fld, ENTITY e 
where fv.TemplateField = fld.TemplateFieldID and  fld.Entity = e.EntityID;

delete 
From VCLib.T_TEMPLATE_FIELD fld
	using ENTITY e where  fld.Entity = e.EntityID;

delete 
From VCLib.T_Report rep
	using ENTITY e where  rep.EntityID = e.EntityID;

DELETE 
FROM VCLib.T_USER_SEARCHES  us
	using ENTITY e where  us.EntityID = e.EntityID;

delete  
from VCLib.T_ENTITIES_ATTRIBUTES e
	using ENTITY ee where  e.EntityID = ee.EntityID;

delete  
from EHR.T_EHR_REFERENCE e
	using ENTITY ee where  e.Entities = ee.EntityID;

delete 
from VCLib.T_ENTITIES e
	using ENTITY ee where  e.EntityID = ee.EntityID;

drop table ENTITY;