
DROP PROCEDURE GrabarCabCtrlFuelProc
GO
CREATE PROCEDURE GrabarCabCtrlFuelProc
(   
    @SITEID              UD_IDSITE,
    @DATEPROCE		 UD_FECHA,
    @USERID		 UD_USERID,
    @CORRNBR             int
)

AS
BEGIN


   DECLARE @ERROR Integer
   DECLARE @TSTAMP timestamp
   DECLARE @ROWCOUNT Integer
   SELECT @ERROR=0   


    BEGIN TRAN

    IF(EXISTS(SELECT * FROM OP_CTRLFUEL WHERE SITEID=@SITEID AND DATEPROCE=@DATEPROCE))
    BEGIN 
	-- SE ELIMINA EL DETALLE
	DELETE FROM OP_CTRLFUELDET WHERE SITEID=@SITEID AND DATEPROCE=@DATEPROCE

	IF (@@error!=0 OR @@ROWCOUNT=0)
    	BEGIN
        	RAISERROR  20000 'Error eliminando en OP_CTRLFUELDET'
        	ROLLBACK TRAN
        	RETURN(1)
	END

	-- DE ELIMINA LA CABECERA	
	DELETE FROM OP_CTRLFUEL WHERE SITEID=@SITEID AND DATEPROCE=@DATEPROCE

	IF (@@error!=0 OR @@ROWCOUNT=0)
    	BEGIN
        	RAISERROR  20000'Error eliminando en OP_CTRLFUEL'
        	ROLLBACK TRAN
        	RETURN(1)
	END

    END	

    INSERT INTO OP_CTRLFUEL(SITEID,DATEPROCE,STATUS,USERID)
    VALUES(@SITEID,@DATEPROCE,0,@USERID)
 
    IF (@@error!=0 OR @@ROWCOUNT=0)
    BEGIN
        RAISERROR  20000 'Error insertando en OP_CTRLTURN'
        ROLLBACK TRAN
        RETURN(1)
    
    END

    /*** Llamada al store de grabado de detalle ******/
    SET EXEC @ERROR=GrabarDetCtrlFuelProc @CORRNBR

    IF (@ERROR!=0)
    BEGIN
       RAISERROR  20000 'Error insertando en OP_CTRLFUELDET'	
       ROLLBACK TRAN
       RETURN(1)               
    END 

   COMMIT TRAN

   RETURN(0)

END


