SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EmailQueue_Failure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EmailQueue_Failure]
GO


create proc dbo.cs_EmailQueue_Failure
	@EmailID uniqueidentifier,
	@FailureInterval int,
	@MaxNumberOfTries int
as
SET Transaction Isolation Level Read UNCOMMITTED
declare @NumberOfTries int
select @NumberOfTries = NumberOfTries + 1 from cs_EmailQueue where EmailID = @EmailID

if @NumberOfTries <= @MaxNumberOfTries
begin
	update cs_EmailQueue set
		NumberOfTries = @NumberOfTries,
		NextTryTime = dateadd(minute, @NumberOfTries * @FailureInterval, getdate())
	where EmailID = @EmailID
end
else
begin
	delete from cs_EmailQueue where EmailID = @EmailID
end
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_EmailQueue_Failure TO public
GO