17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: <strong>Defensive</strong> Error HandlingObviously we'd first need to test this procedure and verify that it can successfullycomplete; a step that I will leave as a simple exercise.In order to test what happens when we have a deadlock, we need to first reset our testdata by rerunning the script in Listing 8-9. Next, start a SERIALIZABLE transactionagainst the CodeDescriptionsChangeLog table, by running the script in Listing 8-10.Rather than invoke our ChangeCodeDescription stored procedure from a secondSSMS session, as before, we need to execute the C# code shown in Listing 8-24, whichinvokes the same stored procedure through our RetryAfterDeadlock method.class RetryAfterDeadlockDemo{static void Main(string[] args){try{using (SqlConnection connection =new SqlConnection("server=(local);trusted_connection=true;database=test8;")){connection.Open();SqlCommand command =connection.CreateCommand();command.CommandText ="EXEC dbo.ChangeCodeDescription@code='IL', @Description='?' ;";command.CommandType = CommandType.Text;SqlCommandExecutor.RetryAfterDeadlock(command, 3);Console.WriteLine("Command succeeded");}}catch (Exception e){288

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!