Ramon Gonzalez
Ramon Gonzalez

Reputation: 251

Deleting and then insert to target table in a transaction

I have the following situation where a stored procedure gathers data and performs the necessary joins and inserts the results into a temp table (ex:#Results)

Now, what I want to do is insert all the records from #Results into a table that was previously created but I first want to remove (truncate/delete) the destination and then insert the results. The catch is putting this process of cleaning the destination table and then inserting the new #Results in a transaction.

I did the following:

BEGIN TRANSACTION

DELETE  FROM PracticeDB.dbo.TransTable

IF @@ERROR <> 0 
    ROLLBACK TRANSACTION
ELSE 
    BEGIN

        INSERT  INTO PracticeDB.dbo.TransTable
                ( 
                   [R_ID]
                  ,[LASTNAME]
                  ,[FIRSTNAME]
                  ,[DATASOURCE]
                  ,[USER_STATUS]
                  ,[Salary]
                  ,[Neet_Stat]
                )
                SELECT  [R_ID]
                      ,[LASTNAME]
                      ,[FIRSTNAME]
                      ,[DATASOURCE]
                      ,[USER_STATUS]
                      ,[Salary]
                      ,[Neet_Stat]
                FROM    #RESULT

        Select @@TRANCOUNT TransactionCount, @@ERROR ErrorCount
        IF @@ERROR <> 0 
            ROLLBACK TRANSACTION

        ELSE 
            COMMIT TRANSACTION

    END

but I know it isn't working properly and I'm having a hard time finding an example like this though I dont know why considering it seems like something common. In this case it still deletes the target table though the insert fails.

More than anything, some guidance would be nice as to best approach this situation or best practices in a similar case (whats best to use and so forth). Thank you in advance...

Upvotes: 3

Views: 1609

Answers (1)

Adam Plocher
Adam Plocher

Reputation: 14233

I'm really not seeing anything wrong with this. So it DOES delete from your TransTable, but doesn't do the insert? Are you sure #RESULT has records in it?

The only thing that I see, is you're checking @@ERROR after Select @@TRANCOUNT TransactionCount, @@ERROR ErrorCount, which means @@ERROR is going to be from your SELECT statement and not the INSERT statement (although I would always expect that to be 0).

For more info on @@ERROR, see: http://msdn.microsoft.com/en-us/library/ms188790.aspx

You should check @@ERROR after each statement.

As far as best practices, I think Microsoft now recommends you use TRY/CATCH instead of checking @@ERROR after each statement (as of SQL 2005 and after). Take a look at Example B here: http://msdn.microsoft.com/en-us/library/ms175976.aspx

Upvotes: 1

Related Questions