IF EXISTS (SELECT * 
           FROM   sysobjects 
           WHERE  id = object_id(N'CT_Contratos_Hist_Ins') 
                  AND OBJECTPROPERTY(id, N'IsTrigger') = 1)
BEGIN
    DROP TRIGGER CT_Contratos_Hist_Ins
END
GO

CREATE TRIGGER [dbo].[CT_Contratos_Hist_Ins]
ON [dbo].[Contratos]
AFTER INSERT
AS 

SET NOCOUNT ON
DECLARE @Id_Cliente					INT
DECLARE @Id_Tarjeta					VARCHAR(10)
DECLARE @Tar_Nro					VARCHAR(25)
DECLARE @Id_Contrato				INT
DECLARE @Item						SMALLINT
DECLARE @Id_Usuario					SMALLINT

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

DECLARE Cur_Contratos_Hist_Ins 
CURSOR FOR
SELECT Id_Contrato, Id_Cliente, Id_Tarjeta, Tar_Nro 
FROM Inserted 
WHERE 
ISNULL(Id_Tarjeta, '') <> '' 
AND ISNULL(Tar_Nro, '') <> ''
	

OPEN Cur_Contratos_Hist_Ins
FETCH NEXT FROM Cur_Contratos_Hist_Ins INTO @Id_Contrato, @Id_Cliente, @Id_Tarjeta, @Tar_Nro
WHILE (@@FETCH_STATUS = 0)
BEGIN
	SET @Item = ISNULL((SELECT MAX(Item) FROM  dbo.Clientes_Hist WHERE Id_Cliente = @Id_Cliente),0) + 1

	/*Graba en CLIENTES_Hist*/
	INSERT INTO Clientes_Hist 
	(Id_Cliente,		Item,			Fecha,
	Id_Tipo_Cli,		Id_Cobrador,	Fecha_Alta,
	Id_Motivo_Est,		Fecha_Baja,		Id_Usuario,
	Id_Cliente_Externo,	Id_Tarjeta,		Tar_Nro,
	Tar_Fecha_Alta,		Tar_Fecha_Baja,	Id_Cliente_Ref,
	Id_Contrato)
	SELECT 
	@Id_Cliente,		@Item,			GETDATE(),
	Id_Tipo_Cli,		Id_Cobrador,	Fecha_Alta,
	Id_Motivo_Est,		Fecha_Baja,		@Id_Usuario,
	Id_Cliente_Externo,	@Id_Tarjeta,	@Tar_Nro,
	GETDATE(),			NULL,			Id_Cliente_Ref,
	@Id_Contrato
	FROM Clientes	
	WHERE Id_Cliente = @Id_Cliente
		
	FETCH NEXT FROM Cur_Contratos_Hist_Ins INTO @Id_Contrato, @Id_Cliente, @Id_Tarjeta, @Tar_Nro
END
CLOSE Cur_Contratos_Hist_Ins
DEALLOCATE Cur_Contratos_Hist_Ins
