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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How can I write transaction with loop while

Author  Topic 

jatuphum
Starting Member

1 Post

Posted - 2009-08-17 : 07:45:15
Hi all,
I want to use transaction with my while loop program.
Because with per loop, I want to Update A Table and Insert B Table.

While @start <= @number
BEGIN
Update TableA SET fieldA1 = @valueA1, fieldA2 = @valueA2

Insert into TableB (fieldB1, fieldB2) values (@valueB1, @valueB2)
SET @start = @start + 1
END

How can I apply transaction with While loop?
Because if any error occur with once loop, I want to rollback previous Update and Insert statement.

Thank you very much.

Sachin.Nand

2937 Posts

Posted - 2009-08-17 : 07:49:55
BEGIN TRY
BEGIN TRANSACTION
While @start <= @number
BEGIN
Update TableA SET fieldA1 = @valueA1, fieldA2 = @valueA2

Insert into TableB (fieldB1, fieldB2) values (@valueB1, @valueB2)
END


COMMIT

END TRY



BEGIN CATCH

IF @@TRANCOUNT<>0
BEGIN
ROLLBACK
SELECT ERROR_MESSAGE()

END
END CATCH

PBUH
Go to Top of Page
   

- Advertisement -