insert EHR.T_EHR_RUS_TREE (EhrRusID)
select er.EhrRusID FROM EHR.T_EHR_RUS er WHERE er.type_ in (SELECT EntityID FROM VCLib.T_ENTITIES WHERE BaseEntity = (SELECT EntityID FROM VCLib.T_ENTITIES WHERE EntName = 'EHR_RUS_TREE'))
and not exists (select tt.EhrRusID from EHR.T_EHR_RUS_TREE tt where er.EhrRusID = tt.EhrRusID)

update tt
 set tt.EhrRusTree = (select top 1 er.EhrRusID FROM EHR.T_EHR_RUS er WHERE er.CodeEHR = tt.PCodeEHR or er.IdEHR = tt.PidEHR and ter.type_ = er.type_)
from EHR.T_EHR_RUS_TREE tt 
join EHR.T_EHR_RUS ter on ter.EhrRusID = tt.EhrRusID
join EHR.T_EHR_RUS per on per.EhrRusID = tt.EhrRusTree
where tt.EhrRusTree is not null and ter.type_ <> per.type_

ALTER TABLE EHR.T_ELEMENT_EHR_REPLACEMENT DROP CONSTRAINT [FK_T_EHR_RUS_T_ELEMENT_EHR_REPLACEMENT_OldEhr];
ALTER TABLE EHR.T_ELEMENT_EHR_REPLACEMENT DROP CONSTRAINT [FK_T_EHR_RUS_T_ELEMENT_EHR_REPLACEMENT_NewEhr];

