IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CP_Listas_Precios_Job_Cargar') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CP_Listas_Precios_Job_Cargar
END
GO


CREATE PROCEDURE CP_Listas_Precios_Job_Cargar @db SYSNAME
AS

DECLARE @jn NVARCHAR(200)
SET @jn =  N'CJ_Listas_Precios_Precio_Nuevo_'+ CAST(@db as NVARCHAR(100))


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 SP CP_Listas_Precios_Precio_Nuevo_Cargar' ;  
  
EXEC msdb.dbo.sp_add_jobstep  
    @job_name =  @jn,  
    @step_name = N'Actulizacion de Precios',  
    @subsystem = N'TSQL',  
	@database_name = @db,
    @command = N'EXEC CP_Listas_Precios_Precio_Nuevo_Cargar',   
    @retry_attempts = 5,  
    @retry_interval = 5 ;  


IF NOT EXISTS ( SELECT * FROM msdb.dbo.sysschedules WHERE name =  N'CS_DiaNuevo') 
BEGIN
	EXEC msdb.dbo.sp_add_schedule  
		@schedule_name = N'CS_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_DiaNuevo';  

EXEC msdb.dbo.sp_add_jobserver  
    @job_name = @jn 

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



