if exists (select * from [dbo].[sysobjects] where [id] = object_id(N'[dbo].[spS_MailAccounts_ForService]') and OBJECTPROPERTY([id], N'IsProcedure') = 1) drop procedure [dbo].[spS_MailAccounts_ForService] GO create procedure [dbo].[spS_MailAccounts_ForService] ( @MinimumInterval int ) as begin begin tran declare @AccountId int select top 1 @AccountId = [AccountId] from ( select [AccountId], datediff(s, getdate(), (dateadd(mi, [TimerInterval], [LastCheckedDateTime]))) as [RefreshDifference] from [dbo].[MailAccounts] with (tablockx, xlock) where ([LockDateTime] is null) and ([IsActive] = 1) ) MA where ([RefreshDifference] <= @MinimumInterval) order by [RefreshDifference] update MailAccounts set LockDateTime = getdate() where (AccountId = @AccountId) commit tran if @AccountId is not null exec [dbo].[spS_MailAccounts] @AccountId end GO grant execute on [dbo].[spS_MailAccounts_ForService] to [public] GO