--select ID, TaxUID,TaxIns from AccFactor with(nolock) where id=23
/****** Object:  Trigger [dbo].[AccFactorDetail_CheckDelete]    Script Date: 02/12/1404 04:42:34 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[AccFactorDetail_CheckDelete]
ON [dbo].[AccFactorDetail] INSTEAD OF DELETE 
	AS
		DECLARE @TaxUID as nvarchar(100)
		DECLARE @TaxIns as nvarchar(100)
		DECLARE @FactorID as bigint
		DECLARE @ID as bigint
		
		DECLARE DelCursor CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
			select ID, FactorID from Deleted
		OPEN DelCursor
		FETCH NEXT FROM DelCursor INTO @ID, @FactorID
		WHILE @@FETCH_STATUS = 0 
		BEGIN
			select @TaxUID=TaxUID,@TaxIns=TaxIns from AccFactor with(nolock) where ID=@FactorID 
			if @TaxUID is null or @TaxUID = CAST(CAST(0x0 AS UNIQUEIDENTIFIER) as nvarchar(100)) or @TaxUID='' or @TaxIns=3
			BEGIN
				delete From dbo.AccFactorDetail where id=@ID
			END
			else
				RAISERROR('امکان حذف فاکتور ارسال شده به سامانه نیست.',16,20) WITH LOG, SETERROR
			FETCH NEXT FROM DelCursor INTO @ID, @FactorID
		END
		CLOSE DelCursor
		DEALLOCATE DelCursor
	return
