alter table akuz.T_HOSPITAL_DESTINATION_DICTIONARY add column scheduleelements varchar(300);

do
$$
declare
    _patindex varchar := '%[0-2][0-9]:[0-5][0-9]%';
    _strangeindex varchar := '%[0-2][0-9]:[0-5][0-9]%-[0-2][0-9]:[0-5][0-9]%';
begin
    create temp table temp_table as
    with recursive cte as (
        select 
            dict.HospitalDestinationDictionaryID,
            dict.Signa,
            substring(dict.Signa from position(':' in dict.Signa) - 2 for 5) as receptionTime,
            replace(dict.Signa, substring(dict.Signa from position(':' in dict.Signa) - 2 for 5), '') as RemainingPart
        from akuz.T_HOSPITAL_DESTINATION_DICTIONARY dict
        where position(':' IN dict.Signa) > 0 
          and dict.Signa not similar to '%N [0-9]%' 
          and dict.Signa not like '%Однократно%'
		  and dict.Signa not like '%По графику до отмены%'
          and dict.Signa not like '%Доз(а) на 1 прием%' 
          and dict.Signa not similar to '%[0-2][0-9]:[0-5][0-9]%-%[0-2][0-9]:[0-5][0-9]%'
          and dict.Signa not similar to '%[0-2][0-9]:[0-5][0-9]%по%[0-2][0-9]:[0-5][0-9]%' 
          and dict.Signa not similar to '%[0-2][0-9]:[0-5][0-9]%до%[0-2][0-9]:[0-5][0-9]%'

        union all

        select 
            HospitalDestinationDictionaryID,
            signa,
            substring(RemainingPart from position(':' in RemainingPart) - 2 for 5),
            replace(RemainingPart, substring(RemainingPart from position(':' in RemainingPart) - 2 for 5), '')
        from cte
        where position(':' in RemainingPart) > 0
    )
    select 
        HospitalDestinationDictionaryID,
        signa,
        string_agg(receptionTime, ';') as times
    from cte
    group by HospitalDestinationDictionaryID, signa;

	update akuz.T_HOSPITAL_DESTINATION_DICTIONARY dict
    set ScheduleElements = temp.times
    from temp_table temp
    where temp.HospitalDestinationDictionaryID = dict.HospitalDestinationDictionaryID;

    drop table if exists temp_table;
end
$$;