
/*------ ATD 194209 ------*/
IF  EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='TR' AND name='VendassCad_I')
	DROP TRIGGER [dbo].[VendassCad_I]
GO

IF  EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='TR' AND name='VendassCad_U')
	DROP TRIGGER [dbo].[VendassCad_U]
GO

CREATE TRIGGER [dbo].[VendassCad_I] ON [dbo].[VENDASSCAD] FOR INSERT AS 
BEGIN 
	INSERT INTO MonitorFinancProprio (NordVen) SELECT Numord FROM inserted
	RETURN 
END 

IF NOT EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='U' AND name='MonitorFinancProprio_LOG')
BEGIN
	CREATE TABLE MonitorFinancProprio_LOG(
		NordVen    INTEGER,
		Data       DATETIME,
		Comando    CHAR(1),
		Aplicativo VARCHAR(254),
		Usuario    VARCHAR(254),
		SPID       INTEGER)

END
GO

IF NOT EXISTS (SELECT 1 FROM SYSINDEXES WHERE name='IDX_MonitorFinancProprio_Log')
	CREATE INDEX IDX_MonitorFinancProprio_Log ON MonitorFinancProprio_Log (NordVen)
GO

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='TR' AND name='MonitorFinancProprio_I')
	DROP TRIGGER [dbo].[MonitorFinancProprio_I]
GO

CREATE TRIGGER [dbo].[MonitorFinancProprio_I] ON [dbo].[MonitorFinancProprio] FOR INSERT AS 
BEGIN 
	INSERT INTO MonitorFinancProprio_LOG 
	SELECT NordVen, GETDATE(), 'I', (SELECT program_name FROM sys.dm_exec_sessions where session_id = @@spid), (SELECT host_name FROM sys.dm_exec_sessions where session_id = @@spid), @@spid FROM inserted
END
GO

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='TR' AND name='MonitorFinancProprio_U')
	DROP TRIGGER [dbo].[MonitorFinancProprio_U]
GO

CREATE TRIGGER [dbo].[MonitorFinancProprio_U] ON [dbo].[MonitorFinancProprio] FOR UPDATE AS 
BEGIN 
	INSERT INTO MonitorFinancProprio_LOG 
	SELECT NordVen, GETDATE(), 'U', (SELECT program_name FROM sys.dm_exec_sessions where session_id = @@spid), (SELECT host_name FROM sys.dm_exec_sessions where session_id = @@spid), @@spid FROM inserted
END
GO

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE TYPE='TR' AND name='MonitorFinancProprio_D')
	DROP TRIGGER [dbo].[MonitorFinancProprio_D]
GO

CREATE TRIGGER [dbo].[MonitorFinancProprio_D] ON [dbo].[MonitorFinancProprio] FOR DELETE AS 
BEGIN 
	INSERT INTO MonitorFinancProprio_LOG 
	SELECT NordVen, GETDATE(), 'D', (SELECT program_name FROM sys.dm_exec_sessions where session_id = @@spid), (SELECT host_name FROM sys.dm_exec_sessions where session_id = @@spid), @@spid FROM deleted
END
GO

IF NOT EXISTS (SELECT 1 FROM SYSCOLUMNS WHERE name = 'GUID' and syscolumns.id IN (SELECT ID FROM SYSOBJECTS WHERE TYPE='U' AND name='MonitorFinancProprio'))
BEGIN
	ALTER TABLE MonitorFinancProprio ADD GUID VARCHAR(254)
END
GO