SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE TABLE LogItemCliQuant(
	NumPed         INT,
	Codpro         CHAR(5),
	QuantAnterior  NUMERIC(9,3),
	QuantAtual     NUMERIC(9,3),
    rItemCli       INT,
	DataHora       DATETIME,
	Estacao        CHAR(20))
GO

CREATE TRIGGER ITEMCLICAD_U ON ItemCliCad FOR UPDATE AS

	DECLARE @Estacao CHAR(20), @Quant NUMERIC(9,3)

	IF UPDATE(Quant)
	BEGIN
		SELECT @Quant = Quant FROM INSERTED
		IF @Quant = 0
		BEGIN
			SELECT @Estacao = HostName FROM master.dbo.sysprocesses WHERE spid=@@spid 
	
			INSERT INTO LogItemCliQuant 
				(NumPed, CodPro, QuantAnterior, QuantAtual, rItemCli, DataHora, Estacao)
			SELECT DELETED.NumPed, DELETED.CodPro, DELETED.Quant, INSERTED.Quant, DELETED.Item, GETDATE(), @ESTACAO  
			FROM INSERTED, DELETED
			WHERE INSERTED.Item = DELETED.Item
		END
	END 
GO

ALTER TRIGGER ITEMCLICAD_I ON ITEMCLICAD FOR INSERT AS
BEGIN
	DECLARE @Estacao CHAR(20), @Quant NUMERIC(9,3), @Item INTEGER

	SELECT @Item = MAX(ITEM)+1 FROM ITEMCLICAD
    UPDATE ITEMCLICAD SET ITEM = @Item WHERE ITEM = (SELECT ITEM FROM INSERTED WHERE ITEM=0)

	IF UPDATE(Quant)
	BEGIN
		SELECT @Quant = Quant FROM INSERTED
		IF @Quant = 0
		BEGIN
			SELECT @Estacao = HostName FROM master.dbo.sysprocesses WHERE spid=@@spid 
	
			INSERT INTO LogItemCliQuant 
				(NumPed, CodPro, QuantAnterior, QuantAtual, rItemCli, DataHora, Estacao)
			SELECT INSERTED.NumPed, INSERTED.CodPro, 0, INSERTED.Quant, @Item, GETDATE(), @ESTACAO  
			FROM INSERTED
		END
	END 
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
