text: --DROP TABLE TESTES
  CREATE TABLE TESTES
  (
    CHV       NUMERIC     NOT NULL,
    DESCRICAO VARCHAR(20) NOT NULL
  )
  
  INSERT INTO TESTES(CHV, DESCRICAO) VALUES(1, 'TESTES 1')
  
  SELECT * FROM TESTES
  DELETE FROM TESTES
  
  --1A TENTATIVA
  INSERT INTO TESTES(CHV, DESCRICAO) 
       VALUES( SELECT MAX(CHV) FROM TESTES, 
              'TESTES 1')
  
  
  --2A TENTATIVA
  INSERT INTO TESTES(CHV, DESCRICAO) 
       VALUES( SELECT MAX(CHV) FROM TESTES, 
              'TESTES 1')
  
  
  
  
  
  
  
  
  
  
  INSERT INTO TESTES(CHV, DESCRICAO) 
       VALUES( CAST( (SELECT ISNULL(MAX(CHV),0)+1 FROM TESTES) AS NUMERIC), 
              'TESTES 1')
  
  
  SELECT * FROM TESTES
  
  
  
  
  
  
  
  
  ALTER TABLE TESTES ADD CMPAUX VARCHAR(50)
  
  --DROP TRIGGER TRIGGER TESTES_TRG
  CREATE OR ALTER TRIGGER TESTES_TRG ON TESTES AFTER INSERT AS
  BEGIN
    DECLARE @CHV NUMERIC
    
    SELECT @CHV =CHV
      FROM INSERTED
  
    UPDATE TESTES
       SET CMPAUX = 'LOG: '+CAST(GETDATE() AS VARCHAR)
     WHERE CHV = @CHV
  END
  GO
  
  SELECT * FROM TESTES
  
  INSERT INTO TESTES(CHV, DESCRICAO) 
       VALUES( CAST( (SELECT ISNULL(MAX(CHV),0)+1 FROM TESTES) AS NUMERIC), 
              'TESTES 2')
  
  
  
  
  
  
  
  
  
  
  ALTER TABLE TESTES ADD HRINS VARCHAR(50)
  ALTER TABLE TESTES ADD HRUPD VARCHAR(50)
  
  --DROP TRIGGER TRIGGER TESTES_TRG
  CREATE OR ALTER TRIGGER TESTES_TRG ON TESTES AFTER INSERT, UPDATE AS
  BEGIN
    DECLARE @CHV NUMERIC
    
    SELECT @CHV =CHV
      FROM INSERTED
  
    IF EXISTS(SELECT * FROM INSERTED) AND 
       EXISTS(SELECT * FROM DELETED) 
    BEGIN
      UPDATE TESTES
         SET HRUPD = 'LOGUPD: '+CAST(GETDATE() AS VARCHAR)
       WHERE CHV = @CHV
    END
    ELSE
    BEGIN
    IF EXISTS(SELECT * FROM INSERTED)
      UPDATE TESTES
         SET HRINS = 'LOGINS: '+CAST(GETDATE() AS VARCHAR)
       WHERE CHV = @CHV
    END
  
  END
  GO
  
  SELECT * FROM TESTES
  
  INSERT INTO TESTES(CHV, DESCRICAO) 
       VALUES( CAST( (SELECT ISNULL(MAX(CHV),0)+1 FROM TESTES) AS NUMERIC), 
              'TESTES 3')
  
  UPDATE TESTES
  SET DESCRICAO = 'TESTES DE UPD 333'
  WHERE CHV = 6
  