SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Transaction Handling in While Loop
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

patshaw
Posting Yak Master

177 Posts

Posted - 03/29/2012 :  04:56:11  Show Profile  Reply with Quote

declare @Count int, @intFlag int

set @Count = (select count(ID) from MyTable where [Date] between getdate()-1 and getdate())
if @Count > 0

begin
	set @intFlag = 1
		while (@intFlag <= @Count)
	begin

		update MyTable1
			set column1 = 1
		where [Date] between getdate()-1 and getdate();
			
		update MyTable2
			set column2 = 1
		where [Date] between getdate()-1 and getdate();
			
	set @intFlag = @intFlag + 1
	end;
end


This is obviously a mock query but the basic layout is the same as one I have in production. Where should BEGIN, COMMIT, ROLLBACK transaction be placed so that if an error is encountered all work from previous iterations is rolled back? I am assuming the transaction should start outside of the loop but would just like clarification on the best way this should be approached.

Thanks.

RickD
Slow But Sure Yak Herding Master

United Kingdom
3560 Posts

Posted - 03/29/2012 :  05:10:19  Show Profile  Reply with Quote

declare @Count int, @intFlag int

begin try
set @Count = (select count(ID) from MyTable where [Date] between getdate()-1 and getdate())
if @Count > 0

begin
	set @intFlag = 1

begin transaction

		while (@intFlag <= @Count)
	begin

		update MyTable1
			set column1 = 1
		where [Date] between getdate()-1 and getdate();
			
		update MyTable2
			set column2 = 1
		where [Date] between getdate()-1 and getdate();
			
	set @intFlag = @intFlag + 1
	end;

commit

end

end try

begin catch
if @@trancount > 0 rollback
end catch


Edited by - RickD on 03/29/2012 05:11:03
Go to Top of Page

patshaw
Posting Yak Master

177 Posts

Posted - 03/29/2012 :  06:05:00  Show Profile  Reply with Quote
Thanks Rick, I'll give it a go.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000