do $$
Declare
    sqltext text;
BEGIN

    select 'INSERT INTO FIES.T_TP_TYPE_DEPENDENCY_SETTING (TpTypeDependencySettingID ,TpType ,SectionDependSettings) SELECT gen_random_uuid(), tt.TpTypeID, sds.SectionDependSettingsID FROM FIES.T_TP_TYPE tt join FIES.T_SECTION_DEPEND_SETTINGS sds on ' ||
  (select string_agg('(sds.' || p.SectionAlias::text || ' = tt.' || p.SectionAlias::text || ' or sds.' || p.SectionAlias::text || ' is null and tt.' || p.SectionAlias::text || ' is null)', ' and ')
   from FIES.T_PLAN_SECTION p
   where p.SectionDependType = 0)::text || ' group by tt.TpTypeID, sds.SectionDependSettingsID'
        into sqltext;

    EXECUTE sqltext;

END;
$$ LANGUAGE plpgsql;
