SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Azimi
-- Create date: 1401/12/1
-- Description:	Expand New/Edited records
-- =============================================

--DROP TRIGGER [dbo].[OnDelete]
--GO
--DROP TRIGGER [dbo].[OnInsertUpdate]
--GO

CREATE TRIGGER dbo.OnInsertUpdate
   ON  dbo.AccWarehouseDelivery 
   AFTER INSERT, Update
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for trigger here
	
	delete AccWarehouseExpandDelivery where ParentID in (select ID from inserted)

	DECLARE @ID as bigint
	DECLARE @SerialFrom as NVARCHAR(20)
	DECLARE @SerialTo as NVARCHAR(20)
	DECLARE @NSerialFrom as bigint
	DECLARE @NSerialTo as bigint
	DECLARE @Serial as bigint
	DECLARE @SerialRightNumverLen as int

	select @SerialRightNumverLen=NumberValue from AppSetting where Name like 'Warehouse.SerialRightNumverLen' 

	DECLARE myCursor CURSOR FOR Select ID, VSerialFrom, VSerialTo from inserted 

	OPEN myCursor
	FETCH NEXT FROM myCursor INTO @ID, @SerialFrom, @SerialTo
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @SerialFrom=RTRIM(@SerialFrom)
		SET @SerialTo=RTRIM(@SerialTo)
		set @NSerialFrom = Power(cast(10 as bigint), @SerialRightNumverLen+1) + CAST ( Right(@SerialFrom, @SerialRightNumverLen) as bigint)
		set @NSerialTo = Power(cast(10 as bigint), @SerialRightNumverLen+1) + CAST ( Right(@SerialTo, @SerialRightNumverLen) as bigint)

		delete AccWarehouseExpandDelivery where ParentID=@ID

		SET @Serial=@NSerialFrom
		while @Serial <= @NSerialTo
		BEGIN
			Insert Into AccWarehouseExpandDelivery(ParentID,Serial) Values(@ID, @Serial)
			SET @Serial=@Serial+1
		END

		FETCH NEXT FROM myCursor INTO @ID, @SerialFrom, @SerialTo
	END
	CLOSE myCursor
	DEALLOCATE myCursor

END
GO


CREATE TRIGGER dbo.OnDelete
   ON  dbo.AccWarehouseDelivery 
   AFTER DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for trigger here
	delete AccWarehouseExpandDelivery where ParentID in (select ID from deleted)
END
GO
