
/*------ ATD 398840 ------*/
IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'LOG_ALTERACAO_ATUAITEM_NFS_TEMP')
 BEGIN
	CREATE TABLE LOG_ALTERACAO_ATUAITEM_NFS_TEMP(
		NumPed INT, 
		NumOrd INT,
		NumNota CHAR(13),
		Serie CHAR(3),
		CodPro CHAR(5),
		Item CHAR(5),
		Data DATETIME, 
		Comando VARCHAR(4000), 
		Sistema VARCHAR(100), 
		Estacao VARCHAR(100), 
		Usuario VARCHAR(100),
		Observacao VARCHAR(100) )
 END
GO

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE NAME = 'Monitorar_Alteracao_AtuaItem_NFS_Ficha_398840')
	DROP TRIGGER Monitorar_Alteracao_AtuaItem_NFS_Ficha_398840
GO

CREATE TRIGGER Monitorar_Alteracao_AtuaItem_NFS_Ficha_398840 ON ItNFSaiCad FOR INSERT, UPDATE AS
BEGIN
	SET NOCOUNT ON 
	Declare @Comando varchar(4000), @ExecStr varchar(50), @Estacao varchar(100), 
			@Usuario varchar(100), @Sistema varchar(100)
			
	CREATE TABLE #inputbuffer (  EventType varchar(30), Paramet int, EventInfo varchar(4000) ) 
	SET @ExecStr = 'DBCC INPUTBUFFER(' + STR(@@SPID) + ')' 
	INSERT INTO #inputbuffer
			
	EXEC (@ExecStr)
			
	SET @Comando = (SELECT EventInfo FROM #inputbuffer)
	DROP TABLE #inputbuffer
			
	SELECT @Estacao = LEFT(host_name,100), 
			@Usuario = LEFT(login_name,100), 
			@Sistema = LEFT(program_name,100)
	FROM sys.dm_exec_sessions 
	where session_id = @@spid
	INSERT INTO LOG_ALTERACAO_ATUAITEM_NFS_TEMP(NumPed, NumOrd, NumNota, Serie, CodPro, Item, Data, Comando, Sistema, Estacao, Usuario, Observacao) 
        SELECT N.NumPed, N.NumOrd, N.NumNota, N.Serie, I.CodPro, I.Item, GETDATE(), @Comando, @Sistema, @Estacao, @Usuario, 'Alterou AtuaItem 1 para 0'
        FROM Inserted I
            JOIN Deleted D ON D.NumOrd = I.NumOrd AND D.Item = I.Item 
            JOIN NFSaidaCad N ON N.NumOrd = I.NumOrd
        WHERE N.Atualiz = 1 AND N.DtCancel IS NULL AND I.AtuaItem = 0 and D.AtuaItem = 1
	SET NOCOUNT OFF
	RETURN
END
GO

