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)


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 SYSTEM_USER = 'SUPER_ADMIN_'
    SET @Id_Usuario = -1
ELSE
	SET @Id_Usuario = ISNULL(  (SELECT [NO] FROM Seg_User WHERE LTRIM(RTRIM( LTRIM(RTRIM(LastName)) + ' ' + LTRIM(RTRIM(FirstName)) )) = SYSTEM_USER ) , 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
