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

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

CREATE TRIGGER COMPL_PROD_ITEMCOLE
ON ITEMCOLE
FOR INSERT
AS
DECLARE @V_TXOBSITMSOL VARCHAR(2000);
DECLARE @V_IDAPROVITMSOLGR VARCHAR(1);
BEGIN
   SELECT @V_IDAPROVITMSOLGR = ISNULL(IDAPROVITMSOLGR, 'N')
     FROM PARASUPRI, INSERTED
    WHERE PARASUPRI.CDFILIAL = INSERTED.CDFILIAL;

   IF @V_IDAPROVITMSOLGR = 'S' BEGIN
      SET @V_TXOBSITMSOL = NULL;
      SELECT @V_TXOBSITMSOL = SUBSTRING(MAX(CONVERT(VARCHAR, TXOBSITMSOL)), 1, 1000)
        FROM ITEMSOLI
       WHERE TXOBSITMSOL IS NOT NULL
         AND EXISTS (SELECT 1
                       FROM INSERTED
                      WHERE INSERTED.CDREGIAO = (SELECT CDREGIAO FROM FILIAL WHERE FILIAL.CDFILIAL = ITEMSOLI.CDFILSOLI)
                        AND ITEMSOLI.DTPROGENTR BETWEEN INSERTED.DTINIVALITM AND INSERTED.DTFINVALITM
                        AND INSERTED.CDPRODUTO = ITEMSOLI.CDPRODUTO);
       UPDATE ITEMCOLE
          SET ITEMCOLE.DSOBSITMCOL = @V_TXOBSITMSOL
         FROM INSERTED
        WHERE INSERTED.CDFILIAL = ITEMCOLE.CDFILIAL
          AND INSERTED.NRCOLEPRECO = ITEMCOLE.NRCOLEPRECO
          AND INSERTED.CDREGIAO = ITEMCOLE.CDREGIAO
          AND INSERTED.CDFORNECED = ITEMCOLE.CDFORNECED
          AND INSERTED.CDPRODUTO = ITEMCOLE.CDPRODUTO
          AND INSERTED.CDMARCA = ITEMCOLE.CDMARCA;
   END;
END;
GO
-- VERSAO --
EXEC ATUVEROBJ 'COMPL_PROD_ITEMCOLE','5.40.001';
GO