/* SYSJOBS */
DECLARE @job_id                     UNIQUEIDENTIFIER = NULL,
	      @name                       NVARCHAR(128) = NULL,
	      @enabled                    TINYINT = 1,
	      @description                NVARCHAR(512) = NULL,
	      @start_step_id              INT = 1,
	      @category_id                INT,
	      @owner_sid                  VARBINARY(85) = NULL,
	      @notify_level_eventlog      INT = 0,
	      @notify_level_email         INT = 0,
	      @notify_level_netsend       INT = 0,
	      @notify_level_page          INT = 0,
	      @delete_level               INT = 0,
	      @categoryname               NVARCHAR(128) = NULL,
	      @categorytype               VARCHAR(12) = NULL,
	      @categoryclass              INT,
	      @loginname                  NVARCHAR(128) = NULL,
/* NOT USED FOR NOW */
	      @notify_email_operator_id   INT = 0,
	      @notify_netsend_operator_id INT = 0,
	      @notify_page_operator_id    INT = 0,
/* SYSJOBSTEP */	      
	      @step_id                    INT = NULL,
	      @step_name                  NVARCHAR(128),
	      @subsystem                  NVARCHAR(40),
	      @command                    NVARCHAR(MAX) = NULL,
	      @flags                      INT,
	      @additional_parameters      NVARCHAR(MAX) = NULL,
	      @cmdexec_success_code       INT = 0,
	      @on_success_action          TINYINT,
	      @on_success_step_id         INT = 0,
	      @on_fail_action             TINYINT,
	      @on_fail_step_id            INT = 0,
	      @server                     NVARCHAR(128) = NULL,
	      @database_name              NVARCHAR(128) = NULL,
	      @database_user_name         NVARCHAR(128) = NULL,
	      @retry_attempts             INT = 0,
	      @retry_interval             INT = 0,
	      @os_run_priority            INT,
	      @output_file_name           NVARCHAR(200) = NULL,
	      @last_run_outcome           INT,
	      @last_run_duration          INT,
	      @last_run_retries           INT,
	      @last_run_date              INT,
	      @last_run_time              INT,
	      @proxy_id                   INT = NULL,
	      @proxyname                  NVARCHAR(128) = NULL,
        @cmd                        VARCHAR(MAX),
        @path                       VARCHAR(200),
/* SYSSCHEDULES */
        @freq_type                  INT,
        @freq_interval              INT,
	      @freq_subday_type           INT,
	      @freq_subday_interval       INT,
	      @freq_relative_interval     INT,
        @freq_recurrence_factor     INT,
        @active_start_date          INT,
        @active_end_date            INT,
	      @active_start_time          INT,
	      @active_end_time            INT,     
/* CUSTOM */
        @code_job                   NVARCHAR(10) = NULL

    DECLARE c_jobs CURSOR LOCAL FORWARD_ONLY STATIC FOR
     SELECT sj.job_id,sj.name, sj.[enabled], sj.[description], sj.start_step_id, sj.category_id, sj.owner_sid, sj.notify_level_eventlog, sj.notify_level_email, sj.notify_level_netsend, sj.notify_level_page, sj.notify_email_operator_id, sj.notify_netsend_operator_id, sj.notify_page_operator_id, sj.delete_level
       FROM msdb.dbo.sysjobs sj
        JOIN msdb.dbo.[syscategories] sc ON sc.[category_id] = sj.[category_id]
WHERE 1=1
  AND LOWER(sj.name) NOT LIKE '%distribution%'
  AND LOWER(sj.name) NOT LIKE '%subscription%'
  AND LOWER(sj.name) NOT LIKE '%replication%'
  AND LOWER(sj.name) NOT LIKE '%ActivePos_read-%'
  AND sj.name LIKE '%IndexOptimize %'
  AND sc.[name] NOT LIKE '%REPL%'
  ORDER BY sj.name
  
 
OPEN c_jobs

FETCH NEXT FROM c_jobs
           INTO @job_id, @name, @enabled, @description, @start_step_id, @category_id, @owner_sid, @notify_level_eventlog, @notify_level_email, @notify_level_netsend, @notify_level_page, @notify_email_operator_id, @notify_netsend_operator_id, @notify_page_operator_id, @delete_level

WHILE @@fetch_status = 0
BEGIN

            SET @path = 'D:\dbjobs\'+@name+'.sql'
            
			DECLARE @cleanCmd VARCHAR(8000)= 'del "'+@path+'"';
			DECLARE @catchOutput TABLE(output VARCHAR(max));

			INSERT INTO @catchOutput ([output])
			EXEC [sys].[xp_cmdshell] @cleanCmd;

			EXEC HCITools.dbo.aps_File_Delete @path = @path; -- nvarchar(max)
			

            SET @code_job = SUBSTRING(@name,0,CHARINDEX('-',@name,0)-1)
           
            SET @cmd = '/* Drop existing standard schedule for job */'+CHAR(13)+CHAR(10)+
                       'declare @schedule_id int'+CHAR(13)+CHAR(10)+
                       'declare c_schedules cursor local forward_only static for'+CHAR(13)+CHAR(10)+
                       '    select ss.schedule_id'+CHAR(13)+CHAR(10)+
                       '      from msdb.dbo.sysjobschedules sjs'+CHAR(13)+CHAR(10)+
                       'INNER JOIN msdb.dbo.sysschedules ss'+CHAR(13)+CHAR(10)+
                       '        ON sjs.schedule_id = ss.schedule_id'+CHAR(13)+CHAR(10)+
                       '       AND ss.name NOT LIKE ''%#SPEC#'''+CHAR(13)+CHAR(10)+
                       'INNER JOIN msdb.dbo.sysjobs sj'+CHAR(13)+CHAR(10)+
                       '        ON sjs.job_id = sj.job_id'+CHAR(13)+CHAR(10)+
                       '     WHERE sj.name = N'''+REPLACE(@name,'''','''''')+''''+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'open c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'FETCH NEXT FROM c_schedules into @schedule_id'+CHAR(13)+CHAR(10)+
                       'while @@fetch_status = 0'+CHAR(13)+CHAR(10)+
                       'begin'+CHAR(13)+CHAR(10)+
                       '  IF ((select COUNT(*) from msdb.dbo.sysjobschedules where schedule_id=@schedule_id) = 1)'+CHAR(13)+CHAR(10)+
                       '    EXEC msdb.dbo.sp_delete_schedule @schedule_id=@schedule_id, @force_delete = 1'+CHAR(13)+CHAR(10)+
                       'FETCH NEXT FROM c_schedules into @schedule_id'+CHAR(13)+CHAR(10)+
                       'end'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'close c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'deallocate c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'IF  EXISTS (SELECT job_id FROM msdb.dbo.sysjobs_view WHERE name = N'''+REPLACE(@name,'''','''''')+''')'+CHAR(13)+CHAR(10)+
                       'EXEC msdb.dbo.sp_delete_job @job_name = N'''+REPLACE(@name,'''','''''')+''', @delete_unused_schedule=0'+CHAR(13)+CHAR(10)+
                       'GO'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       '/* Creation Job and Steps*/'+CHAR(13)+CHAR(10)+
                       'BEGIN TRANSACTION'+CHAR(13)+CHAR(10)+
                       'DECLARE @ReturnCode INT'+CHAR(13)+CHAR(10)+
                       'SELECT @ReturnCode = 0'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
                                    
            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
             
            SET @categoryname = NULL
            SET @categoryclass = 1
            SET @categorytype = 'LOCAL'
                        
            SELECT @categoryname = name,@categoryclass = category_class, @categorytype = CASE category_type 
                                              WHEN 1 THEN 'LOCAL' 
                                              WHEN 2 THEN 'MULTI-SERVER'
                                              WHEN 3 THEN 'NONE' END
            FROM msdb.dbo.syscategories WHERE category_id =  @category_id        

            SET @loginname = NULL

            SELECT @loginname = name FROM sys.syslogins WHERE sid = @owner_sid

            /*
                                                      ,  @notify_level_eventlog =  
                                                      ,  @notify_level_email =  
                                                      ,  @notify_level_netsend =  
                                                      ,  @notify_level_page =  
                                                      ,  @notify_email_operator_name =    
                                                      ,  @notify_netsend_operator_name =   
                                                      ,  @notify_page_operator_name =    

            */


            SET @cmd = 'IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'''+REPLACE(@categoryname,'''','''''')+''' AND category_class='+CAST(@categoryclass AS VARCHAR(1))+')'+CHAR(13)+CHAR(10)+
                       'BEGIN'+CHAR(13)+CHAR(10)+
                       'EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N''JOB'', @type=N'''+ @categorytype +''', @name=N'''+REPLACE(@categoryname,'''','''''')+''''+CHAR(13)+CHAR(10)+
                       'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'END'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       '/* Add Job */'+CHAR(13)+CHAR(10)+
                       'DECLARE @jobId BINARY(16)'+CHAR(13)+CHAR(10)+
                       'EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'''+REPLACE(@name,'''','''''')+''', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@enabled=' +CAST(@enabled AS VARCHAR(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@notify_level_eventlog=' +CAST(@notify_level_eventlog AS VARCHAR(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@notify_level_email=' +CAST(@notify_level_email AS VARCHAR(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@notify_level_netsend=' +CAST(@notify_level_netsend AS VARCHAR(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@notify_level_page=' +CAST(@notify_level_page AS VARCHAR(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@delete_level='+CAST(@delete_level AS VARCHAR(2))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)
                       
            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'           
              
            SET @cmd = '@description='+ISNULL('N'''+REPLACE(@description,'''','''''')+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)
            
            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'           
                        
            SET @cmd = '@category_name=N'''+@categoryname+''', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@start_step_id='+CAST(@start_step_id AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                       '@owner_login_name=N'''+@loginname+''', @job_id = @jobId OUTPUT'+CHAR(13)+CHAR(10)+
                       'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)

            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
          
            DECLARE c_jobstep CURSOR LOCAL FORWARD_ONLY STATIC FOR
            SELECT step_id, step_name,	subsystem,	command, flags,	additional_parameters,	cmdexec_success_code,	on_success_action,	on_success_step_id,	on_fail_action,	on_fail_step_id,	[server],	database_name,	database_user_name,	retry_attempts,	retry_interval,	os_run_priority,	output_file_name,	last_run_outcome,	proxy_id
                FROM msdb.dbo.sysjobsteps
               WHERE job_id = @job_id
            ORDER BY step_id
              
            OPEN c_jobstep

            FETCH NEXT FROM c_jobstep
                       INTO @step_id, @step_name,	@subsystem,	@command, @flags,	@additional_parameters,	@cmdexec_success_code,	@on_success_action,	@on_success_step_id,	@on_fail_action,	@on_fail_step_id,	@server,	@database_name,	@database_user_name,	@retry_attempts,	@retry_interval,	@os_run_priority,	@output_file_name,	@last_run_outcome,	@proxy_id

            WHILE @@fetch_status = 0
            BEGIN
                
               SET @proxyname = NULL

               SELECT @proxyname = name FROM msdb.dbo.sysproxies WHERE proxy_id = @proxy_id

               SET @cmd = '/* Add Step */'+CHAR(13)+CHAR(10)+
                          'EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'''+REPLACE(@step_name,'''','''''')+''', '+CHAR(13)+CHAR(10)+CHAR(9)+ CHAR(9)+
                          '@step_id='+CAST(@step_id AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@cmdexec_success_code='+CAST(@cmdexec_success_code AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+  
                          '@on_success_action='+CAST(@on_success_action AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@on_success_step_id='+CAST(@on_success_step_id AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+  
                          '@on_fail_action='+CAST(@on_fail_action AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@on_fail_step_id='+CAST(@on_fail_step_id AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@retry_attempts='+CAST(@retry_attempts AS VARCHAR(30))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@retry_interval='+CAST(@retry_interval AS VARCHAR(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@os_run_priority='+CAST(@os_run_priority AS VARCHAR(3))+', @subsystem=N'''+@subsystem+''', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)
              
              EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
              
              SET @cmd =  '@command='+ISNULL('N'''+REPLACE(@command,'''','''''')+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)
              
              EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
              
              
              SET @cmd =  '@database_name='+ISNULL('N'''+@database_name+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@output_file_name='+ISNULL('N'''+@output_file_name+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@flags='+CAST(@flags as varchar(3))+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@database_user_name='+ISNULL('N'''+@database_user_name+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
                          '@server='+ISNULL('N'''+@server+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)
              
              EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'           
              
              SET @cmd =  '@additional_parameters='+ISNULL('N'''+@additional_parameters+'''','NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          --'@proxy_id='+ISNULL(CAST(@proxy_id as varchar(50)),'NULL')+', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@proxy_id=NULL, '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                          '@proxy_name='+ISNULL('N'''+@proxyname+'''','NULL')+''+CHAR(13)+CHAR(10)+
                          'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)        	

               EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'

               FETCH NEXT FROM c_jobstep
                          into @step_id, @step_name,	@subsystem,	@command, @flags,	@additional_parameters,	@cmdexec_success_code,	@on_success_action,	@on_success_step_id,	@on_fail_action,	@on_fail_step_id,	@server,	@database_name,	@database_user_name,	@retry_attempts,	@retry_interval,	@os_run_priority,	@output_file_name,	@last_run_outcome,	@proxy_id
            end

            close c_jobstep

            deallocate c_jobstep
            
            SET @cmd = 'EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = '+CAST(@start_step_id as varchar(3))+CHAR(13)+CHAR(10)+
                       'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
            
	          EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
	                  	          
	          declare c_schedules cursor local forward_only static for
                    select name,[enabled],freq_type,freq_interval,freq_subday_type,freq_subday_interval,freq_relative_interval,freq_recurrence_factor,active_start_date,active_end_date,active_start_time,active_end_time
                      from msdb.dbo.sysjobschedules sjs
                INNER JOIN msdb.dbo.sysschedules ss
                        ON sjs.job_id = @job_id
                       AND sjs.schedule_id = ss.schedule_id
                       AND ss.name NOT LIKE '%#SPEC#'
                       AND ss.name LIKE @code_job+'%'
  
            open c_schedules

            FETCH NEXT FROM c_schedules
                       into @name,@enabled, @freq_type, @freq_interval, @freq_subday_type, @freq_subday_interval, @freq_relative_interval, @freq_recurrence_factor, @active_start_date, @active_end_date, @active_start_time, @active_end_time
              
            while @@fetch_status = 0
            begin
                        
                SET @cmd = '/* Add Standard Schedule */'+CHAR(13)+CHAR(10)+
                           'EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'''+REPLACE(@name,'''','''''')+''', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
                           '@enabled=' +CAST(@enabled as varchar(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+
		                       '@freq_type=' +CAST(@freq_type as varchar(3)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@freq_interval=' +CAST(@freq_interval as varchar(3)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@freq_subday_type=' +CAST(@freq_subday_type as varchar(1)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@freq_subday_interval=' +CAST(@freq_subday_interval as varchar(2)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@freq_relative_interval=' +CAST(@freq_relative_interval as varchar(2)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@freq_recurrence_factor=' +CAST(@freq_recurrence_factor as varchar(2)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@active_start_date=' +CAST(@active_start_date as varchar(8)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@active_end_date=' +CAST(@active_end_date as varchar(8)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+  
		                       '@active_start_time=' +CAST(@active_start_time as varchar(6)) +', '+CHAR(13)+CHAR(10)+CHAR(9)+CHAR(9)+ 
		                       '@active_end_time=' +CAST(@active_end_time as varchar(6)) +''+CHAR(13)+CHAR(10)+
                           'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
         
	              EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
            
                FETCH NEXT FROM c_schedules
                           into @name,@enabled, @freq_type, @freq_interval, @freq_subday_type, @freq_subday_interval, @freq_relative_interval, @freq_recurrence_factor, @active_start_date, @active_end_date, @active_start_time, @active_end_time
	          end

            close c_schedules

            deallocate c_schedules
            
            SET @cmd = '/* Attach existing specific schedule for job */'+CHAR(13)+CHAR(10)+
                       'declare @enabled_schedule int,'+CHAR(13)+CHAR(10)+
                       '        @schedule_name nvarchar(50)'+CHAR(13)+CHAR(10)+
                       'declare c_schedules cursor local forward_only static for'+CHAR(13)+CHAR(10)+
                       'select enabled, name'+CHAR(13)+CHAR(10)+
                       '  from msdb.dbo.sysschedules'+CHAR(13)+CHAR(10)+
                       ' where name LIKE '''+@code_job+'%'''+CHAR(13)+CHAR(10)+
                       '   and name LIKE ''%#SPEC#'''+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'open c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'FETCH NEXT FROM c_schedules into @enabled_schedule, @schedule_name'+CHAR(13)+CHAR(10)+
                       'while @@fetch_status = 0'+CHAR(13)+CHAR(10)+
                       'begin'+CHAR(13)+CHAR(10)+
                       '  EXEC @ReturnCode = msdb.dbo.sp_attach_schedule @job_id = @jobId, @schedule_name=@schedule_name'+CHAR(13)+CHAR(10)+
                       '  IF(@enabled_schedule = 1)'+CHAR(13)+CHAR(10)+
                       '  begin'+CHAR(13)+CHAR(10)+
                       '    SET @schedule_name = SUBSTRING(@schedule_name,0,LEN(@schedule_name)-5)'+CHAR(13)+CHAR(10)+
                       '    IF EXISTS (select name from msdb.dbo.sysschedules where name = @schedule_name)'+CHAR(13)+CHAR(10)+
                       '      EXEC @ReturnCode = msdb.dbo.sp_update_schedule @name=@schedule_name, @enabled=0'+CHAR(13)+CHAR(10)+
                       '  end'+CHAR(13)+CHAR(10)+
                       '  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+
                       'FETCH NEXT FROM c_schedules into @enabled_schedule, @schedule_name'+CHAR(13)+CHAR(10)+
                       'end'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'close c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'deallocate c_schedules'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
                           
            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
            
            SET @cmd = 'EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N''(local)'''+CHAR(13)+CHAR(10)+
                       'IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback'+CHAR(13)+CHAR(10)+
                       'COMMIT TRANSACTION'+CHAR(13)+CHAR(10)+
                       'GOTO EndSave'+CHAR(13)+CHAR(10)+
                       'QuitWithRollback:'+CHAR(13)+CHAR(10)+
                       '    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION'+CHAR(13)+CHAR(10)+
                       'EndSave:'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+
                       'GO'+CHAR(13)+CHAR(10)

            EXEC HCITools.[dbo].[aps_File_Write_Text]   @data = @cmd, @path = @path,@append = 1, @encoding = 'utf-16'
	          
   FETCH NEXT FROM c_jobs
              into @job_id, @name, @enabled, @description, @start_step_id, @category_id, @owner_sid, @notify_level_eventlog, @notify_level_email, @notify_level_netsend, @notify_level_page, @notify_email_operator_id, @notify_netsend_operator_id, @notify_page_operator_id, @delete_level

end

close c_jobs

deallocate c_jobs
