CREATE OR ALTER TRIGGER TTBCLIENTE_B0I_01 FOR TBCLIENTE
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE CODIGO INTEGER;
BEGIN

    IF (COALESCE(NEW.EMPRESA_VINCULO,0) = 0) THEN
        BEGIN
         NEW.EMPRESA_VINCULO = NEW.CODIGO;
        END
    
    FOR SELECT
        COALESCE((SELECT FIRST 1 E.CODIGO FROM TBESTABELECIMENTO E
                   WHERE E.UF = NEW.UF
                     AND E.SUBSTITUTO_TRIBUTARIO = '1'),0) AS CODIGO
        FROM RDB$DATABASE
        INTO :CODIGO
        
        DO
        BEGIN
        
              IF (:CODIGO > 0) THEN
              BEGIN
                  NEW.SUBSTITUIDO_TRIBUTARIO = '1';
              END
        END

END;