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

DROP TRIGGER UPDTHREADINFO
GO

CREATE TRIGGER UPDTHREADINFO
ON BKGTHREAD
FOR INSERT 
AS
   DECLARE @NEW_DSREMOTEADDR VARCHAR(15);
   DECLARE @NEW_DSREMOTEHOST VARCHAR(15);
   DECLARE @NEW_DSREMOTEAPPL VARCHAR(10);
   DECLARE @NEW_DSREMOTEOPER VARCHAR(12);
BEGIN
   DECLARE C_CURSOR CURSOR FOR
      SELECT DSREMOTEADDR, DSREMOTEHOST, DSREMOTEAPPL, DSREMOTEOPER
      FROM SQLWEBTUNNING
      WHERE NRAUDSID = @@SPID
      ORDER BY DTSTARTDATE;
   OPEN C_CURSOR;
   FETCH NEXT FROM C_CURSOR INTO @NEW_DSREMOTEADDR, @NEW_DSREMOTEHOST, @NEW_DSREMOTEAPPL, @NEW_DSREMOTEOPER;   
   CLOSE C_CURSOR;
   DEALLOCATE C_CURSOR;
   IF (@@FETCH_STATUS = 0)
   BEGIN
      DECLARE C_OPER CURSOR FOR
         SELECT CDOPERADOR
         FROM   OPERADOR
         WHERE  CDOPERADOR = @NEW_DSREMOTEOPER;
      OPEN C_OPER;  
      FETCH NEXT FROM C_OPER INTO @NEW_DSREMOTEOPER;
      IF NOT (@@FETCH_STATUS = 0)
      BEGIN
         SET @NEW_DSREMOTEOPER = NULL;       
      END;

      UPDATE BKGTHREAD
      SET DSIPADTHREAD = @NEW_DSREMOTEADDR,
          DSHOSTTHREAD = @NEW_DSREMOTEHOST, 
          DSAPPLTHREAD = @NEW_DSREMOTEAPPL, 
          CDOPERTHREAD = @NEW_DSREMOTEOPER 
      FROM INSERTED
      CLOSE C_OPER;
      DEALLOCATE C_OPER;
   END;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'UPDTHREADINFO','4.11.139';
GO
