IF EXISTS ( SELECT * FROM SYS.OBJECTS WHERE TYPE = 'TR' 
              AND name = 'CT_Cbtes_Est_Hist')
BEGIN
    DROP TRIGGER dbo.CT_Cbtes_Est_Hist 
END
GO



CREATE TRIGGER CT_Cbtes_Est_Hist ON Cbtes
FOR UPDATE 
AS 
SET NOCOUNT ON
DECLARE @Id_Trans				INT
        ,@Id_Estado_Cbte	    SMALLINT
		,@Login					sysname
		,@Id_Usuario			SMALLINT
		,@User					VARCHAR(100)

IF dbo.CF_xParam('User_Sql_Hab') = '1'
BEGIN
	DECLARE tri_cbt_est_cur CURSOR FOR
		SELECT I.Id_Trans, I.Id_Estado_Cbte FROM Deleted D, Inserted I
			WHERE I.Id_Trans = D.Id_Trans
			AND I.Id_Estado_Cbte <> D.Id_Estado_Cbte

	IF ISNUMERIC(SYSTEM_USER) = 1
		SET @Id_Usuario =  SYSTEM_USER 
    ELSE
		SET @Id_Usuario =  0

	OPEN tri_cbt_est_cur
	FETCH NEXT FROM tri_cbt_est_cur INTO @Id_Trans, @Id_Estado_Cbte 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO Cbtes_Estados_Hist (Id_Trans,Fecha,Id_Estado_Cbte,Id_Usuario) VALUES (@Id_Trans,GETDATE(),@Id_Estado_Cbte,@Id_Usuario)
		FETCH NEXT FROM tri_cbt_est_cur INTO @Id_Trans, @Id_Estado_Cbte 
	END
	CLOSE tri_cbt_est_cur
	DEALLOCATE tri_cbt_est_cur
END
