ove ove - 1 year ago 130
C# Question

SQL server recovery mechanism

I have a service application in C# which queries data from one database and inserts it into another SQL database.

Sometimes, the MSSQLSERVER service crashed for unknown reason and my application will crash as well. I want to do a SQL recovery mechanism that where I check to make sure the sqlconnection state is fine before i write to the database but how i do that?

I tried stopping MSSQLSERVER service and sqlconnection.State is always open even when the MSSQLSERVER service is stopped.

Answer Source

I think that the approach you chose is not very good.

If your application is some kind of scheduled job, let it crash. No database - no work can be done. This is ok to crash in this case. Next time it runs and db is up it will do its thing. You can also implement retries.

If your application is a windows service inside and some kind of scheduled timer, you just make sure that your service doesn't crash by handling SqlExcpetion. Retry again until server is up.

Also, you might want to use distributed transactions. To guarantee integrity of the copy procedure, but whether you need it or not, depends on the requirements.

[Edit] In response to retry question.

var attemptNumber = 0;
while (true)
        using (var connection = new SqlConnection())

            // do the job
    catch (SqlException exception)
        // log exception
        if (attemptNumber > 3)
            throw; // let it crash
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download