DROP TABLE AKUZ.T_CDA_MEDCERTIFICATE_EHR_RUS_EJQDJJQAQJ_LINK

select EntityID 
INTO #ENTITY
from VCLib.T_ENTITIES e
where e.EntName in (
'CDA_MEDCERTIFICATE_EHR_RUS_EJQDJJQAQJ_LINK'
)
and e.[Schema] = 'AKUZ'

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

Delete ctx
From VCLib.T_USER_CONTEXTS ctx
	join #ENTITY e on  ctx.EntityID = e.EntityID

delete del 
from VCLib.T_DELETED_OBJECT del
	join #ENTITY e on  del.Entities = e.EntityID

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

delete fld
From VCLib.T_TEMPLATE_FIELD fld
	join #ENTITY e on  fld.Entity = e.EntityID

delete rep
From VCLib.T_Report rep
	join #ENTITY e on  rep.EntityID = e.EntityID

delete g_rep
    FROM VCLib.T_GENERIC_REPORT g_rep
	join #ENTITY e on  g_rep.Entities = e.EntityID

DELETE us 
FROM VCLib.T_USER_SEARCHES  us
	join #ENTITY e on  us.EntityID = e.EntityID

delete er
from EHR.T_EHR_REFERENCE er
	join #ENTITY ee on  er.Entities = ee.EntityID

delete e 
from VCLib.T_ENTITIES_ATTRIBUTES e
	join #ENTITY ee on  e.EntityID = ee.EntityID

delete e 
from VCLib.T_ENTITIES e
	join #ENTITY ee on  e.EntityID = ee.EntityID

drop table #ENTITY