
update AKUZ.T_HOSPITAL_DESTINATION_LEK_COMPONENT lekComp
set name = 
    coalesce(trn.namerus, medService.name, mnn.namerus, '') ||
    case 
        when medService.medicalserviceid IS NULL AND mf.name IS NOT NULL 
        then ' ' || mf.name
        else ''
    end ||
    case 
        when doseView.value IS NOT NULL 
        then ' ' || doseView.value
        else ''
    end
    from AKUZ.T_HOSPITAL_DESTINATION_LEK_COMPONENT lekComp1
    left join akuz.S_DLO_DoseView doseView ON doseView.id = lekComp1.doseviewnew
    left join pharm.T_C_MNN mnn ON mnn.cmnnid = lekComp1.cmnn
    left join pharm.T_C_TRN trn ON trn.ctrnid = lekComp1.ctrn
    left join pharm.T_MEDICATION_FORMS mf ON mf.medicationformsid = lekComp1.medicationforms
    left join akuz.T_MEDICAL_SERVICE medService ON medService.medicalserviceid = lekComp1.procedure
    WHERE lekComp.hospitaldestinationlekcomponentid = lekComp1.hospitaldestinationlekcomponentid;

update akuz.T_HOSPITAL_DESTINATION hd
set name = coalesce((
    select string_agg(
        trim(
            coalesce(trn.namerus, medService.name, mnn.namerus, '') ||
            case 
                when medService.medicalserviceid is null and mf.name is not null
                then ' ' || mf.name
                else ''
            end ||
            case 
                when doseView.value is not null
                then ' ' || doseView.value
                else ''
            end
        ),
        ' + '
        order by lek.basecomponent
    )
    FROM akuz.T_HOSPITAL_DESTINATION_LEK_COMPONENT lek
    left join akuz.S_DLO_DoseView doseView ON doseView.id = lek.doseviewnew
    left join pharm.T_C_TRN trn ON lek.ctrn = trn.ctrnid
    left join akuz.T_MEDICAL_SERVICE medService ON lek.procedure = medService.medicalserviceid
    left join pharm.T_C_MNN mnn ON lek.cmnn = mnn.cmnnid
    left join pharm.T_MEDICATION_FORMS mf ON lek.medicationforms = mf.medicationformsid
    where lek.hospitaldestination = hd.medicalrecordid
      and (
          trn.namerus is not null
          OR medService.name is not null
          OR mnn.namerus is not null
      )
), '');