SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[STOKGUNCELLE_TRG] ON [dbo].[STOK] 
FOR UPDATE
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @STOKID int, @ESKISTOKID int
	DECLARE @SALISBFIYAT float,@ESKISALISBFIYAT float
	DECLARE @MALIYETGUNCELLE nvarchar(1)

	DECLARE @SALFUPDATED_CURSOR CURSOR 
	SET @SALFUPDATED_CURSOR = CURSOR FAST_FORWARD FOR
		SELECT I.STOKID, I.SALISBFIYAT,D.STOKID, D.SALISBFIYAT
		FROM INSERTED I FULL JOIN 
			 DELETED D ON I.STOKID = D.STOKID
		WHERE I.SALISBFIYAT<>D.SALISBFIYAT	 
	OPEN @SALFUPDATED_CURSOR
	FETCH NEXT FROM @SALFUPDATED_CURSOR INTO @STOKID, @SALISBFIYAT, @ESKISTOKID, @ESKISALISBFIYAT

	IF @@ROWCOUNT <> 0 
	BEGIN 

		SELECT @MALIYETGUNCELLE=VALUESTR FROM [CONFIG] WHERE PROGNAME='MEDISOFT' AND SECTIONSTR='Stok' AND KEYNAME='Fiyat Listesindeki Maliyet Tutari Otomatik Guncellensin'

		WHILE @@FETCH_STATUS = 0 AND ISNULL(@MALIYETGUNCELLE,'') = '1'  
		BEGIN
			IF ISNULL(@STOKID,0)<>0  EXEC TITEMSONALISGUNCELLE @STOKID
			FETCH NEXT FROM @SALFUPDATED_CURSOR INTO @STOKID, @SALISBFIYAT, @ESKISTOKID, @ESKISALISBFIYAT
		END
	END
	CLOSE @SALFUPDATED_CURSOR
	DEALLOCATE @SALFUPDATED_CURSOR

	DECLARE @SFIYAT float,@ESKISFIYAT float
	DECLARE @SATIFGUNCELLE nvarchar(1)

	DECLARE @SATFUPDATED_CURSOR CURSOR 
	SET @SATFUPDATED_CURSOR = CURSOR FAST_FORWARD FOR
		SELECT I.STOKID, I.SFIYAT1,D.STOKID, D.SFIYAT1
		FROM INSERTED I FULL JOIN 
			 DELETED D ON I.STOKID = D.STOKID
		WHERE I.SFIYAT1<>D.SFIYAT1
	OPEN @SATFUPDATED_CURSOR
	FETCH NEXT FROM @SATFUPDATED_CURSOR INTO @STOKID, @SFIYAT, @ESKISTOKID, @ESKISFIYAT

	IF @@ROWCOUNT <> 0 
	BEGIN 
		SELECT @SATIFGUNCELLE=VALUESTR FROM [CONFIG] WHERE PROGNAME='MEDISOFT' AND SECTIONSTR='Stok' AND KEYNAME='Fiyat Listesindeki Hastane Fiyatı Satış Fiyatından Güncellensin'

		WHILE @@FETCH_STATUS = 0 AND ISNULL(@SATIFGUNCELLE, '') = '1'  
		BEGIN
			IF ISNULL(@STOKID,0) <> 0  
			 UPDATE TITEM SET ITEMFIYATI = @SFIYAT WHERE STOKID = @STOKID AND IIPTAL = 0
			FETCH NEXT FROM @SATFUPDATED_CURSOR INTO @STOKID, @SFIYAT, @ESKISTOKID, @ESKISFIYAT
		END
	END
	CLOSE @SATFUPDATED_CURSOR
	DEALLOCATE @SATFUPDATED_CURSOR
END
GO


