开发者

Transactions within loop within stored procedure

开发者 https://www.devze.com 2022-12-08 15:34 出处:网络
I\'m working on a procedure that will update a large number of items on a remote server, using records from a local database.Here\'s the pseudocode.

I'm working on a procedure that will update a large number of items on a remote server, using records from a local database. Here's the pseudocode.

CREATE PROCEDURE UpdateRemoteServer
    pre-processing
    get cursor with ID's of records to be开发者_运维技巧 updated
    while on cursor
        process the item

No matter how much we optimize it, the routine is going to take a while, so we don't want the whole thing to be processed as a single transaction. The items are flagged after being processed, so it should be possible to pick up where we left off if the process is interrupted.

Wrapping the contents of the loop ("process the item") in a begin/commit tran does not do the trick... it seems that the whole statement

EXEC UpdateRemoteServer

is treated as a single transaction. How can I make each item process as a complete, separate transaction?

Note that I would love to run these as "non-transacted updates", but that option is only available (so far as I know) in 2008.


EXEC procedure does not create a transaction. A very simple test will show this:

create procedure usp_foo
as
begin
  select @@trancount;
end
go

exec usp_foo;

The @@trancount inside usp_foo is 0, so the EXEC statement does not start an implicit transaction. If you have a transaction started when entering UpdateRemoteServer it means somebody started that transaction, I can't say who.

That being said, using remote servers and DTC to update items is going to perform quite bad. Is the other server also SQL Server 2005 at least? Maybe you can queue the requests to update and use messaging between the local and remote server and have the remote server perform the updates based on the info from the message. It would perform significantly better because both servers only have to deal with local transactions, and you get much better availability due to the loose coupling of queued messaging.

Updated

Cursors actually don't start transactions. The typical cursor based batch processing is usually based on cursors and batches updates into transactions of a certain size. This is fairly common for overnight jobs, as it allows for better performance (log flush throughput due to larger transaction size) and jobs can be interrupted and resumed w/o losing everithing. A simplified version of a batch processing loop is typically like this:

create procedure usp_UpdateRemoteServer
as
begin
  declare @id int, @batch int;
  set nocount on;
  set @batch = 0;

  declare crsFoo cursor 
    forward_only static read_only 
    for 
    select object_id 
    from sys.objects;

  open crsFoo;

  begin transaction
  fetch next from crsFoo into @id ;
  while @@fetch_status = 0
  begin

    -- process here

    declare @transactionId int;
    SELECT @transactionId = transaction_id 
      FROM sys.dm_tran_current_transaction;
    print @transactionId;

    set @batch = @batch + 1
    if @batch > 10
    begin
      commit;
      print @@trancount;
      set @batch = 0;
      begin transaction;
    end
    fetch next from crsFoo into @id ;
  end
  commit;
  close crsFoo;

  deallocate crsFoo;
end
go

exec usp_UpdateRemoteServer;

I ommitted the error handling part (begin try/begin catch) and the fancy @@fetch_status checks (static cursors actually don't need them anyway). This demo code shows that during the run there are several different transactions started (different transaction IDs). Many times batches also deploy transaction savepoints at each item processed so they can skip safely an item that causes an exception, using a pattern similar to the one in my link, but this does not apply to distributed transactions since savepoints and DTC don't mix.


EDIT: as pointed out by Remus below, cursors do NOT open a transaction by default; thus, this is not the answer to the question posed by the OP. I still think there are better options than a cursor, but that doesn't answer the question.

Stu

ORIGINAL ANSWER:

The specific symptom you describe is due to the fact that a cursor opens a transaction by default, therefore no matter how you work it, you're gonna have a long-running transaction as long as you are using a cursor (unless you avoid locks altogether, which is another bad idea).

As others are pointing out, cursors SUCK. You don't need them for 99.9999% of the time.

You really have two options if you want to do this at the database level with SQL Server:

  1. Use SSIS to perform your operation; very fast, but may not be available to you in your particular flavor of SQL Server.

  2. Because you're dealing with remote servers, and you're worried about connectivity, you may have to use a looping mechanism, so use WHILE instead and commit batches at a time. Although WHILE has many of the same issues as a cursor (looping still sucks in SQL), you avoid creating the outer transaction.

Stu


Are yo running this only from within sql server, or from an app? if so, get the list to be processed, then loop in the app to only process for the subsets as required.

Then the transaction should be handled by your app, and should only lock the items being updated/pages the items are in.


NEVER process one item at a time in a loop when you are doing transactional work. You can loop through records processing groups of them but never ever do one record at a time. Do set-based inserts instead and your performance will change from hours to minutes or even seconds. If you are using a cursor to insert update or delete and it isn't handling at least 1000 rowa in each statement (not one at atime) you are doing the wrong thing. Cursors are an extremely poor practice for such thing.


Just an idea ..

  • Only process a few items when the procedure is called (e.g. only get the TOP 10 items to process)
  • Process those

Hopefully, this will be the end of the transaction.

Then write a wrapper that calls the procedure as long as there is more work to do (either use a simple count(..) to see if there are items or have the procedure return true indicating that there is more work to do.

Don't know if this works, but maybe the idea is helpful.

0

精彩评论

暂无评论...
验证码 换一张
取 消