Thursday, April 16, 2009

Sql Sever SMO Programming

Reference of msdn: http://msdn.microsoft.com/en-us/library/ms162129.aspx

Add the dll references below for sql server operation first:
Microsoft.SqlSever.ConnectionInfo.dll
Microsoft.SqlSever.Management.Sdk.Sfc.dll
Microsoft.SqlSever.Smo.dll
Microsoft.SqlSever.SqlEnum.dll

As one of my sql scheduled job has activeX script task and some times failed, we need to check the status of the job. If the job failed, we need to re run the job. So I write below an example to check whether the job need to re run.

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

static void Main(string[] args)
{
ServerConnection conn = new ServerConnection(@"myServerInstance", "myUserName", "myPassword");
Server srv = new Server(conn);
JobServer agent = srv.JobServer;
foreach (Job e in agent.Jobs)
{
if (e.Name == "My Job scheduled" && e.CurrentRunStatus.ToString() == "Idle" && e.LastRunOutcome.ToString()=="Failed")
{
e.Start();
}
}

If don't use SMO, we can create views:

SELECT *
FROM OPENQuery(myServer1,'exec msdb.dbo.sp_get_composite_job_info')
Union
SELECT *
FROM OPENQuery(myServer2,'exec msdb.dbo.sp_get_composite_job_info')
...

Then query this view.

No comments: