Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
patshaw
Posting Yak Master
177 Posts |
Posted - 2012-03-29 : 04:56:11
|
[code]declare @Count int, @intFlag intset @Count = (select count(ID) from MyTable where [Date] between getdate()-1 and getdate())if @Count > 0begin 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[/code]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
3608 Posts |
Posted - 2012-03-29 : 05:10:19
|
[code]declare @Count int, @intFlag intbegin tryset @Count = (select count(ID) from MyTable where [Date] between getdate()-1 and getdate())if @Count > 0begin set @intFlag = 1begin 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;commitendend trybegin catchif @@trancount > 0 rollbackend catch[/code] |
 |
|
patshaw
Posting Yak Master
177 Posts |
Posted - 2012-03-29 : 06:05:00
|
Thanks Rick, I'll give it a go. |
 |
|
|
|
|