SQL job result in c#

2019-09-02 11:35发布

问题:

I have this small code using SQL Server Agent to Run a Remote Package Programmatically on the Server. But the problem with the code is that even if the job out come is failure, but job was executed successfully. so this program always works fine.

I want to know if I can actually capture the job result in C#.. Any thoughts?

namespace LaunchSSISPackageAgent_CS
{
  class Program
  {
static void Main(string[] args)
{
  SqlConnection jobConnection;
  SqlCommand jobCommand;
  SqlParameter jobReturnValue;
  SqlParameter jobParameter;
  int jobResult;

  jobConnection = new SqlConnection("Data Source=(local);Initial Catalog=msdb;Integrated Security=SSPI");
  jobCommand = new SqlCommand("sp_start_job", jobConnection);
  jobCommand.CommandType = CommandType.StoredProcedure;

  jobReturnValue = new SqlParameter("@RETURN_VALUE", SqlDbType.Int);
  jobReturnValue.Direction = ParameterDirection.ReturnValue;
  jobCommand.Parameters.Add(jobReturnValue);

  jobParameter = new SqlParameter("@job_name", SqlDbType.VarChar);
  jobParameter.Direction = ParameterDirection.Input;
  jobCommand.Parameters.Add(jobParameter);
  jobParameter.Value = "RunSSISPackage";

  jobConnection.Open();
  jobCommand.ExecuteNonQuery();
  jobResult = (Int32)jobCommand.Parameters["@RETURN_VALUE"].Value;
  jobConnection.Close();

  switch (jobResult)
  {
    case 0:
      Console.WriteLine("SQL Server Agent job, RunSISSPackage, started successfully.");
      break;
    default:
      Console.WriteLine("SQL Server Agent job, RunSISSPackage, failed to start.");
      break;
  }
  Console.Read();
}

}

回答1:

You could try running sp_help_job afterwards

http://technet.microsoft.com/en-us/library/ms186722(SQL.90).aspx