declare @sql nvarchar(max)
select @sql = 'INSERT INTO [FIES].[T_TARIFF_DEPENDECY_SETTING] ([TariffDependecySettingID] ,[BaseTariff] ,[SectionDependSettings]) SELECT NEWID(), bt.BaseTariffID, sds.SectionDependSettingsID FROM FIES.T_BASE_TARIFF bt join FIES.T_SECTION_DEPEND_SETTINGS sds on ' +
  (select dbo.Joint('(sds.[' + p.SectionAlias + '] = bt.[' + p.SectionAlias + '] or sds.[' + p.SectionAlias + '] is null and bt.[' + p.SectionAlias + '] is null)', ' and ')
   from FIES.T_PLAN_SECTION p
   where p.SectionDependType = 0) + ' group by bt.BaseTariffID, sds.SectionDependSettingsID'
exec sp_executesql @sql
