I have a store procedure like below:
DECLARE @FinalQuery varchar(max), @TableName varchar(200)
DECLARE ListTable CURSOR FOR SELECT....
DECLARE @isError bit=0
OPEN ListTable
FETCH NEXT FROM ListTable INTO @TableName
WHILE @@FETCH_STATUS=0
BEGIN
//Some code to generate @FinalQuery to merge data into table @TableName
BEGIN TRY
EXEC(@FinalQuery)
END TRY
BEGIN CATCH
Set @IsError = 1
//Some code to write error to log file.
END CATCH
FETCH NEXT FROM ListTable INTO @TableName
END
CLOSE ListTable
DEALLOCATE ListTable
Now, I want to add transaction and rollback to my store procedure. I want all dynamic @FinalQuery query to be executed, and finally, when it finish, if any error exists ( @IsError=1) then rollback everything. How can i do that ?