DECLARE @jn NVARCHAR(200)
SET @jn =  N'CJ_Stat'

DECLARE @db NVARCHAR(128);
SET @db = DB_NAME();


IF EXISTS ( SELECT * FROM msdb.dbo.sysjobs WHERE name = @jn)
BEGIN
	EXEC msdb.dbo.sp_delete_job @job_name = @jn  , @delete_history = 1 , @delete_unused_schedule = 1  
END
   

EXEC msdb.dbo.sp_add_job  
    @job_name = @jn,
	@description = N'Ejecuta el job de calculo de estadisticas de CleverSoft' ;  
  
EXEC msdb.dbo.sp_add_jobstep  
    @job_name =  @jn,  
    @step_name = N'Calculo de Estadisticas de CleverSoft',  
    @subsystem = N'TSQL',  
	@database_name = @db,
    @command = N'DECLARE @Fecha DATE; SET @Fecha = GETDATE() - 1; EXEC CP_Stat @Fecha ',   
    @retry_attempts = 5,  
    @retry_interval = 5 ;  


IF NOT EXISTS ( SELECT * FROM msdb.dbo.sysschedules WHERE name =  N'CS_CP_Stat_DiaNuevo') 
BEGIN
	EXEC msdb.dbo.sp_add_schedule  
		@schedule_name = N'CS_CP_Stat_DiaNuevo',  
		@freq_type = 4,  
		@freq_interval = 1,
		@active_start_time = 000000 ;  

END
 

EXEC msdb.dbo.sp_attach_schedule  
   @job_name = @jn,   
   @schedule_name = N'CS_CP_Stat_DiaNuevo';  

EXEC msdb.dbo.sp_add_jobserver  
    @job_name = @jn 

--SELECT name FROM msdb.dbo.sysjobs WHERE name =  @jn



