IF OBJECT_ID('sp_FollowUpTantargy') IS NOT NULL BEGIN
  DROP PROCEDURE sp_FollowUpTantargy
END;
GO

CREATE PROCEDURE sp_FollowUpTantargy
  @intezmenyId int,
  @aktTanevId int,
  @kovetkezoTanevId int,
  @tantargyId int
AS
BEGIN

IF (@tantargyId = 0)
	BEGIN
		INSERT INTO T_TANTARGY_OSSZES (
     C_GYAKORLATI
    ,C_NEV
    ,C_ROVIDNEV
    ,C_TARGYKATEGORIA
    ,C_TANORANKIVULI
    ,C_IMPORTALT
    ,C_FOTARGYE
	  ,C_ALTANTARGYKENTNYOMTATVANYBAN
	  ,C_NEVNYOMTATVANYBAN
	  ,C_FOTARGYID
    ,C_INTEZMENYID
    ,C_TANEVID
    ,TOROLT
    ,SERIAL
    ,LASTCHANGED
    ,CREATED
    ,MODIFIER
    ,CREATOR
	  ,NNID
	  ,ELOZOTANEVIREKORDID
  ) SELECT 
     C_GYAKORLATI AS C_GYAKORLATI
    ,C_NEV AS C_NEV
    ,C_ROVIDNEV AS C_ROVIDNEV
	  ,IIF((SELECT COUNT(1) FROM T_TARGYKATEGORIATIPUS_OSSZES WHERE C_ALTANEVID = @kovetkezoTanevId AND ID = t.C_TARGYKATEGORIA) = 0, 1197, t.C_TARGYKATEGORIA) AS C_TARGYKATEGORIA
	  ,C_TANORANKIVULI AS C_TANORANKIVULI
	  ,C_IMPORTALT AS C_IMPORTALT
	  ,C_FOTARGYE AS C_FOTARGYE
	  ,C_ALTANTARGYKENTNYOMTATVANYBAN AS C_ALTANTARGYKENTNYOMTATVANYBAN
	  ,C_NEVNYOMTATVANYBAN AS C_NEVNYOMTATVANYBAN
	  ,(SELECT ID FROM T_TANTARGY_OSSZES WHERE ELOZOTANEVIREKORDID = t.C_FOTARGYID) AS C_FOTARGYID 
    ,@intezmenyID AS C_INTEZMENYID
    ,@kovetkezoTanevId AS C_TANEVID
    ,TOROLT AS TOROLT
    ,0 AS SERIAL
    ,GETDATE() AS LASTCHANGED
    ,GETDATE() AS CREATED
    ,MODIFIER AS MODIFIER
    ,MODIFIER AS CREATOR
    ,NULL AS NNID
	  ,t.ID AS ELOZOTANEVIREKORDID
    FROM T_TANTARGY_OSSZES t WHERE C_TANEVID = @aktTanevId AND C_INTEZMENYID = @intezmenyId AND t.TOROLT='F'
		AND 0 = (SELECT COUNT(1) FROM T_TANTARGY_OSSZES WHERE C_TANEVID = @kovetkezoTanevId AND C_INTEZMENYID = @intezmenyId AND ELOZOTANEVIREKORDID = t.ID)
	END
ELSE
	BEGIN
		UPDATE kovetkezo SET
     kovetkezo.C_GYAKORLATI = aktiv.C_GYAKORLATI
    ,kovetkezo.C_NEV = aktiv.C_NEV
    ,kovetkezo.C_ROVIDNEV = aktiv.C_ROVIDNEV
    ,kovetkezo.C_TARGYKATEGORIA = IIF((SELECT COUNT(1) FROM T_TARGYKATEGORIATIPUS_OSSZES WHERE C_ALTANEVID = @kovetkezoTanevId AND ID = aktiv.C_TARGYKATEGORIA) = 0, 1197, aktiv.C_TARGYKATEGORIA)
    ,kovetkezo.C_TANORANKIVULI = aktiv.C_TANORANKIVULI
    ,kovetkezo.C_IMPORTALT = aktiv.C_IMPORTALT
    ,kovetkezo.C_FOTARGYE = aktiv.C_FOTARGYE
	  ,kovetkezo.C_ALTANTARGYKENTNYOMTATVANYBAN = aktiv.C_ALTANTARGYKENTNYOMTATVANYBAN
	  ,kovetkezo.C_NEVNYOMTATVANYBAN = aktiv.C_NEVNYOMTATVANYBAN
	  ,kovetkezo.C_FOTARGYID = (SELECT ID FROM T_TANTARGY_OSSZES WHERE ELOZOTANEVIREKORDID = aktiv.C_FOTARGYID)
    ,kovetkezo.TOROLT = aktiv.TOROLT
	FROM T_TANTARGY_OSSZES kovetkezo
	INNER JOIN T_TANTARGY_OSSZES aktiv ON aktiv.C_INTEZMENYID = kovetkezo.C_INTEZMENYID AND aktiv.C_TANEVID = @aktTanevId AND aktiv.ID = @tantargyId AND aktiv.TOROLT='F'
	WHERE kovetkezo.C_INTEZMENYID = @intezmenyId AND kovetkezo.C_TANEVID = @kovetkezoTanevId AND kovetkezo.ELOZOTANEVIREKORDID = @tantargyId AND kovetkezo.TOROLT='F'
	END
END
GO
