IF EXISTS(SELECT * FROM sysobjects O, sysusers U
	WHERE
		o.name = 'GRAVA_ATUA_CONTCTBL_LANCCUSTO' and
		type = 'TR'                and
		u.uid = o.uid              and
		u.name = USER)
		DROP TRIGGER GRAVA_ATUA_CONTCTBL_LANCCUSTO
GO

CREATE TRIGGER GRAVA_ATUA_CONTCTBL_LANCCUSTO
ON LANCCONT
FOR UPDATE
AS
DECLARE @V_OLD_CDEMPRESA   VARCHAR(02);
DECLARE @V_OLD_NRLANCCONT  VARCHAR(12);
DECLARE @V_OLD_NRSEQLANC   VARCHAR(06);
DECLARE @V_OLD_CDCONTCTBL  VARCHAR(20);

DECLARE @V_NEW_CDEMPRESA   VARCHAR(02);
DECLARE @V_NEW_NRLANCCONT  VARCHAR(12);
DECLARE @V_NEW_NRSEQLANC   VARCHAR(06);
DECLARE @V_NEW_CDCONTCTBL  VARCHAR(20);

DECLARE @V_IDCONTCCUS      VARCHAR(02);

BEGIN
   DECLARE C_CURSOR CURSOR FOR
      SELECT DEL.CDEMPRESA, DEL.NRLANCCONT,
             DEL.NRSEQLANC, DEL.CDCONTCTBL,

             INS.CDEMPRESA, INS.NRLANCCONT,
             INS.NRSEQLANC, INS.CDCONTCTBL
        FROM INSERTED INS, DELETED DEL
       WHERE INS.NRLANCCONT  = DEL.NRLANCCONT
         AND INS.NRSEQLANC   = DEL.NRSEQLANC
         AND INS.CDEMPRESA   = DEL.CDEMPRESA;
       OPEN C_CURSOR;
       FETCH NEXT FROM C_CURSOR INTO @V_OLD_CDEMPRESA, @V_OLD_NRLANCCONT, @V_OLD_NRSEQLANC, @V_OLD_CDCONTCTBL,
                                     @V_NEW_CDEMPRESA, @V_NEW_NRLANCCONT, @V_NEW_NRSEQLANC, @V_NEW_CDCONTCTBL
       WHILE @@FETCH_STATUS = 0 BEGIN
          SELECT @V_IDCONTCCUS = IDCONTCCUS
            FROM CONTCTBL
           WHERE CDCONTCTBL = @V_NEW_CDCONTCTBL;

          IF @V_IDCONTCCUS <> 'O' BEGIN
             UPDATE LANCCCUSTO
                SET CDCONTCTBL = @V_NEW_CDCONTCTBL
               FROM INSERTED
              WHERE LANCCCUSTO.CDEMPRESA   = @V_OLD_CDEMPRESA
                AND LANCCCUSTO.NRLANCCONT  = @V_OLD_NRLANCCONT
                AND LANCCCUSTO.NRSEQLANC   = @V_OLD_NRSEQLANC;
          END;

          FETCH NEXT FROM C_CURSOR INTO @V_OLD_CDEMPRESA, @V_OLD_NRLANCCONT, @V_OLD_NRSEQLANC, @V_OLD_CDCONTCTBL,
                                        @V_NEW_CDEMPRESA, @V_NEW_NRLANCCONT, @V_NEW_NRSEQLANC, @V_NEW_CDCONTCTBL;
       END;
       CLOSE C_CURSOR;
       DEALLOCATE C_CURSOR;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'GRAVA_ATUA_CONTCTBL_LANCCUSTO','5.30.000';
GO
