IF EXISTS
  (SELECT *
   FROM sys.objects
   WHERE object_id = OBJECT_ID(N'[dbo].[sp_DropSectionDependSettingsWithChilds]')
     AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_DropSectionDependSettingsWithChilds] 
GO

CREATE PROCEDURE [dbo].[sp_DropSectionDependSettingsWithChilds] 
    @SectionDependSettingsID uniqueidentifier,
    @PlanPeriod uniqueidentifier
AS 
BEGIN
    SET NOCOUNT ON; 
    DECLARE @sql nvarchar(max)

    set @sql = 'DELETE dl
      FROM fies.T_SECTION_DEPEND_SETTINGS sds
      JOIN fies.T_SECTION_DEPEND_SETTINGS dl ON  '+
      (select [dbo].[Joint]('(sds.' + sectionAlias+'= dl.' + sectionAlias + ' OR sds.' + sectionAlias + ' IS NULL)', ' AND ')
       from FIES.T_PLAN_SECTION) + ' and dl.PlanPeriod = sds.PlanPeriod' + '
      where sds.SectionDependSettingsID = ''' + CAST(@SectionDependSettingsID AS VARCHAR(36)) + ''' and sds.PlanPeriod = ''' + cast(@PlanPeriod as varchar(36)) + ''''

    exec sp_executesql @sql 
END 
GO
