CREATE OR REPLACE TRIGGER PEDICLILIBERAR_IUD BEFORE INSERT OR UPDATE OF SitVen ON PediCliCad FOR EACH ROW 
DECLARE 
	nCount INTEGER; 
	sNome CHAR(50); 
BEGIN 
	nCount := 0; 
	sNome := ' '; 
	IF :NEW.SitVen = '1' THEN 
		SELECT SUBSTR(Nome, 1, 50) INTO sNome FROM Cliente_r WHERE OID = :NEW.CodClie; 
		SELECT COUNT(*) INTO nCount FROM PediCliLiberar WHERE NumPed = :NEW.NumPed AND Filial = :NEW.Filial; 
		IF nCount > 0 THEN 
			UPDATE PediCliLiberar SET DtPedido = :NEW.DtPedido, ValPed = :NEW.ValPed WHERE NumPed = :NEW.NumPed AND Filial = :NEW.Filial; 
		ELSE 
			INSERT INTO PediCliLiberar (Filial, NumPed, DtPedido, CodClie, Nome, ValPed,CodVend) VALUES (:NEW.Filial, :NEW.NumPed, :NEW.DtPedido,:NEW.CodClie, sNome, :NEW.ValPed, :NEW.CodVend); 
		END IF; 
	ELSE 
		IF :NEW.SitVen <> '1' AND :OLD.SitVen = '1' THEN 
			SELECT COUNT(*) INTO nCount FROM PediCliLiberar WHERE NumPed = :NEW.NumPed AND Filial = :NEW.Filial; 
			IF nCount > 0 THEN 
				DELETE FROM PediCliLiberar WHERE NumPed = :NEW.NumPed AND Filial = :NEW.Filial; 
			END IF; 
		END IF; 
	END IF; 
END;
/
