How to Identify whether SQL job is successfully executed or not in C#

后端 未结 3 1766
滥情空心
滥情空心 2020-12-06 14:30

I have an C# method to execute a SQL job. It executes the SQL job successfully. And the code works perfect.

And I\'m using standard SQL stored procedure msdb.d

3条回答
  •  旧时难觅i
    2020-12-06 14:41

    You need to run stored proceedure msdb.dbo.sp_help_job

         private int CheckAgentJob(string connectionString, string jobName) {
            SqlConnection dbConnection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand();
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText = "msdb.dbo.sp_help_job";
            command.Parameters.AddWithValue("@job_name", jobName);
            command.Connection = dbConnection;
            using (dbConnection)
            {
                dbConnection.Open();      
                using (command){
                    SqlDataReader reader = command.ExecuteReader();
                    reader.Read();
                    int status = reader.GetInt32(21); // Row 19 = Date Row 20 = Time 21 = Last_run_outcome
                    reader.Close();
                    return status;
                }
            }
         }
    
    enum JobState { Failed = 0, Succeeded = 1, Retry = 2, Cancelled = 3, Unknown = 5};
    

    Keep polling on Unknown, until you get an answer. Lets hope it is succeeded :-)

提交回复
热议问题