等待存储过程中的延迟

时间:2015-09-02 14:03:17

标签: sql-server tsql stored-procedures

我想在删除5条记录后添加等待存储过程的延迟。 @rowstoremove = 5。我想通过一份工作来执行这个程序,并希望确保在1小时左右的时间内删除了多少条记录。

非常感谢任何帮助。

CREATE Procedure [dbo].DeleteRecords
    @rowstoremove int = 0,
    @executeOnce  char(1) = 'Y'
As
Begin
    Declare @err int, 
            @rowCount int,
            @rowsToDelete int

    -- Load records of lowest id for a given duplicate set into a temp table
    select  
        Min(iD) keptID, UserId, AccountId, AddressId 
    into    
        #tmpKept
    from 
        adm.useraccess
    group by 
        UserId, AccountId, AddressId
    order by 1

    select *
    into #tmpRemoved
    from adm.useraccess A
    where not exists (select keptID 
                      from #tmpKept T 
                      where T.keptID = A.ID) 

    select @rowsToDelete = count(*) 
    from #tmpRemoved 

    if @rowstoremove = 0 
       select @rowstoremove = @rowsToDelete

    if @executeOnce = 'Y' 
    begin
        select 
            'Job Starting at ' + convert(varchar(255), getdate()) + '. Deleting a total of ' + convert(varchar(255), @rowstoremove) + ' rows'   

        delete top (@rowstoremove) adm.useraccess   
        from adm.useraccess A, #tmpRemoved R
        where A.ID = R.ID

        set @rowCount  = @@ROWCOUNT

        select 'Duplicate rows removed: ' +  convert(varchar(255), @rowCount) +' on: (' + convert(varchar(255), getdate())  + ')'   

        return
    end

    if @executeOnce !='Y'
    begin
        select 'Job Starting at ' + convert(varchar(255), getdate()) + '. Deleting a total of ' +  convert(varchar(255), @rowsToDelete) +' rows in groups of ' + convert(varchar(255), @rowstoremove)   + ' rows at a time' 

        set @rowCount = 1

        -- Remove duplicate records
        while @rowCount > 0 
        begin
            delete top (@rowstoremove) adm.useraccess   
            from adm.useraccess A, #tmpRemoved R
            where A.ID = R.ID

            set @rowCount = @@ROWCOUNT

            select 'Duplicate rows removed: ' +  convert(varchar(255), @rowCount) +' on: (' + convert(varchar(255), getdate())  + ')'   
        end
    end
end

1 个答案:

答案 0 :(得分:0)

使用waitfor(https://msdn.microsoft.com/en-us/library/ms187331.aspx):

WAITFOR 
{
    DELAY 'time_to_pass' 
  | TIME 'time_to_execute' 
  | [ ( receive_statement ) | ( get_conversation_group_statement ) ] 
    [ , TIMEOUT timeout ]
}