do $$
Declare
    sqltext text;
BEGIN

    select 'INSERT INTO FIES.T_TARIFF_DEPENDECY_SETTING (TariffDependecySettingID ,BaseTariff ,SectionDependSettings) SELECT gen_random_uuid(), bt.BaseTariffID, sds.SectionDependSettingsID FROM FIES.T_BASE_TARIFF bt join FIES.T_SECTION_DEPEND_SETTINGS sds on ' ||
  (select string_agg('(sds.' || p.SectionAlias::text || ' = bt.' || p.SectionAlias::text || ' or sds.' || p.SectionAlias::text || ' is null and bt.' || p.SectionAlias::text || ' is null)', ' and ')
   from FIES.T_PLAN_SECTION p
   where p.SectionDependType = 0)::text || ' group by bt.BaseTariffID, sds.SectionDependSettingsID'
        into sqltext;

    EXECUTE sqltext;

END;
$$ LANGUAGE plpgsql;
