declare @EntityID int = (select top(1) e.EntityID from VCLib.T_ENTITIES e where e.EntName = 'EHR_RUS_NK0467' and e.[Schema] = 'EHR')
declare @EhrRusRefBooksID_int int
EXEC @EhrRusRefBooksID_int = sp_GenerateIdForEntity 'EHR.EHR_RUS_REF_BOOKS';

insert into EHR.T_EHR_RUS_REF_BOOKS (EhrRusRefBooksID, Deleted, Code, [Name], CurrVersion, UpdateDate, Entities, OID)
select @EhrRusRefBooksID_int,0, 'NK0467', 'РР. Клинические группы больных злокачественными новообразованиями', '1.1','20260327 04:09:13', @EntityID, '1.2.643.5.1.13.13.99.2.146'
where not exists (select * from EHR.T_EHR_RUS_REF_BOOKS er where er.Entities = @EntityID and er.Deleted = 0 and er.CurrVersion = '1.1')

declare @EhrRusRefBooksID int = (select top(1) er.EhrRusRefBooksID from EHR.T_EHR_RUS_REF_BOOKS er where er.Entities = @EntityID and er.Deleted = 0 and er.CurrVersion = '1.1')

DECLARE @EhrRusIDMax int
EXEC @EhrRusIDMax = sp_GenerateIdForEntity 'EHR.EHR_RUS_NK0467', 'PrimaryKey', 6;
select @EhrRusRefBooksID as EhrRusRefBooks
	, 0 + @EhrRusIDMax as EhrRusID
	, 7 as [IdEHR]
	, 'Iб' as [NameEHR]
into #NK0467
union all
select @EhrRusRefBooksID, 1 + @EhrRusIDMax , 6, 'Ia' union all
select @EhrRusRefBooksID, 2 + @EhrRusIDMax , 5, 'IV' union all
select @EhrRusRefBooksID, 3 + @EhrRusIDMax , 4, 'III' union all
select @EhrRusRefBooksID, 4 + @EhrRusIDMax , 3, 'II' union all
select @EhrRusRefBooksID, 5 + @EhrRusIDMax , 2, 'IIа'

insert into EHR.T_EHR_RUS_NK0467 (EhrRusRefBooks, EhrRusID, IdEHR, NameEHR)
select EhrRusRefBooks
	, EhrRusID
	, IdEHR
	, NameEHR
from #NK0467 t
where not exists (select * from EHR.T_EHR_RUS_NK0467 er where er.IdEHR = t.IdEHR and er.EhrRusRefBooks = @EhrRusRefBooksID)

drop table #NK0467

update otc
set otc.ONK_GROUP = ern.EhrRusID
from AKUZ.T_ONK_TREATMENT_CASE otc
inner join EHR.T_EHR_RUS_NK0467 ern
    on ern.NameEHR = case
                        when otc.ONK_GROUP = 11 then 'Ia'
                        when otc.ONK_GROUP = 12 then 'Iб'
                        when otc.ONK_GROUP = 20 then 'II'
                        when otc.ONK_GROUP = 30 then 'III'
                        when otc.ONK_GROUP = 40 then 'IV'
                    end