user2135285
user2135285

Reputation: 125

Track Database Status Change sql server

I want to Track database status changed in sql server . in my solution ,I have a database that is offline due to restore from primary server . i want to get hint in my application(C#) when database is offline and when is online. (like sql notification event) . Thanks .

Upvotes: 0

Views: 828

Answers (1)

antew
antew

Reputation: 979

One way is to check the state of the database using a timer from your application

 private void timer1_tick(object sender,EventArgs e)
    {
    if(CheckDatabaseState() == "ONLINE")
       MessageBox.Show("db is online");
    else
    MessageBox.Show("db is NOT online");
    }

    Public string CheckDatabaseState()
    {
        string Constr = @"Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=master;";

         string sql = string.Format("SELECT Name, state_desc FROM sys.databases where name = '{0}'", dbName);     

                SqlConnection conn;
                SqlCommand comm;
                SqlDataAdapter adapter;
                DataSet ds = new DataSet();

                conn = new SqlConnection(Constr);
                comm = new SqlCommand(sql, conn);
                adapter = new SqlDataAdapter(comm);
                adapter.Fill(ds);

                return ds.Tables[0]["state_desc"].ToString();
    }

Let me know if this helps,

Upvotes: 1

Related Questions