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

CREATE TRIGGER GRAVA_CDCONTCTBL_LANCCUSTO
ON LANCCCUSTO
INSTEAD OF INSERT
AS

DECLARE @V_NRLANCCONT  VARCHAR(12);
DECLARE @V_NRSEQLANC   VARCHAR(06);
DECLARE @V_CDEMPRESA   VARCHAR(02);
DECLARE @V_CDCONTCTBL  VARCHAR(20);
DECLARE @V_CDFILIAL    VARCHAR(04);
DECLARE @V_CDCENTCUST  VARCHAR(04);
DECLARE @V_DTCOMPCUSTO DATE;
DECLARE @V_IDCONTCCUS  VARCHAR(01);
DECLARE @V_VRLANCCUST  FLOAT;

BEGIN
   DECLARE C_CURSOR CURSOR FOR
      SELECT INS.CDEMPRESA,  INS.NRLANCCONT,  INS.NRSEQLANC, INS.CDFILIAL,
             INS.CDCENTCUST, INS.DTCOMPCUSTO, INS.VRLANCCUST
        FROM INSERTED INS
       WHERE (CDEMPRESA+NRLANCCONT+NRSEQLANC+CDFILIAL+CDCENTCUST+DTCOMPCUSTO)
      NOT IN (SELECT CDEMPRESA+NRLANCCONT+NRSEQLANC+CDFILIAL+CDCENTCUST+DTCOMPCUSTO FROM DELETED);
      OPEN C_CURSOR;
      FETCH NEXT FROM C_CURSOR INTO @V_CDEMPRESA,  @V_NRLANCCONT,  @V_NRSEQLANC, @V_CDFILIAL,
                                    @V_CDCENTCUST, @V_DTCOMPCUSTO, @V_VRLANCCUST;
      WHILE @@FETCH_STATUS = 0 BEGIN
         SELECT @V_CDCONTCTBL = CDCONTCTBL
           FROM LANCCONT
          WHERE CDEMPRESA  = @V_CDEMPRESA
            AND NRLANCCONT = @V_NRLANCCONT
            AND NRSEQLANC  = @V_NRSEQLANC;
         SELECT @V_IDCONTCCUS = IDCONTCCUS
           FROM CONTCTBL
          WHERE CDCONTCTBL = @V_CDCONTCTBL;

         IF @V_IDCONTCCUS <> 'O' BEGIN
            INSERT INTO LANCCCUSTO
               (CDEMPRESA, NRLANCCONT, NRSEQLANC, CDFILIAL, CDCENTCUST, DTCOMPCUSTO, CDCONTCTBL, VRLANCCUST)
            VALUES
               (@V_CDEMPRESA, @V_NRLANCCONT, @V_NRSEQLANC, @V_CDFILIAL, @V_CDCENTCUST, @V_DTCOMPCUSTO, @V_CDCONTCTBL, @V_VRLANCCUST);

         END;
         FETCH NEXT FROM C_CURSOR INTO @V_CDEMPRESA,  @V_NRLANCCONT, @V_NRSEQLANC, @V_CDFILIAL,
                                    @V_CDCENTCUST, @V_DTCOMPCUSTO, @V_VRLANCCUST;
      END;
      CLOSE C_CURSOR;
      DEALLOCATE C_CURSOR;
END;
GO

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

