I would suggest that you read the part 1 of this article before going through this one. The major details of the SQLDMO are discussed in the part 1 of this article. We have upgraded the component to be used with SQL Server 7.0. The code in the previous article worked only with the version 6.5 of the SQL Server. More enhancements are made in the new component, the new component is capable of deleting the task automatically once the task has been accomplished. In the previous version, the task once created had to be removed manually by executing a method called “RemoveTask”, but there is no need for such method in the new component as it will delete the task upon successful completion. Furthermore, earlier the task was executed each time a specific date was reached, but now the task will execute only once at a specific date the user will supply to the component. Also, we have demonstrated how to add two steps in the same job. In the previous article the job consisted of only one step, but the new tasks created with the new component shall consist of more than one job step, that is, user can accomplish more than one job within the same task. Now, let's go through the code step by step:
Private Sub Class_Initialize()
On Error Resume Next
NL = Chr$(13) & Chr$(10)
Set oSQLServer = New SQLDMO.SQLServer
oSQLServer.LoginTimeout = 10
The main object is created when the class is initialized, similarly this object shall be deleted from the memory when the class is terminated.
Our main method is known as
AddTask, this method will add a new task to the task scheduler. Note, we have not passed the parameters directly to the function, instead we have used the properties to get the input from the user.
Public Function AddTask()
On Error GoTo errhandler
Disconnect the server if its already connected.
If Server = "" Then
ErrDesc = "You must enter server name."
ElseIf UserID = "" Then
ErrDesc = "You must enter a valid User ID"
ElseIf Password = "" Then
Password = ""
Get values of important parameters from the user, these values are needed to connect to the SQL Server.
oSQLServer.Connect CStr(Server), CStr(UserID), CStr(Password)
Dim oJob As New SQLDMO.Job
Dim idStep As Integer
Idstep will be used to define the total number of steps to be included in the task.
oJob.Name = JobID
Assign a name to the job.
Add the newly created job to the job server. The
JobServer object exposes attributes associated with SQL server agent. SQL Server agent is responsible for executing the scheduled jobs and notifying operators of SQL Server error conditions or other SQL Server execution or job states.
Initially, we have assigned a zero value to the step ID. Because we intend to add two steps in our task, so we run a loop twice.
For idStep = 0 To 2
Dim oJobStep As SQLDMO.JobStep
Set oJobStep = New SQLDMO.JobStep
We have created a new
JobStep object in the statements above. The
JobStep object exposes the attributes of a single SQL Server agent executable job step. SQL Server Agent jobs contain one or more execution units called steps. Each job step contains a textual command, type of execution that specifies command interpretation, and logic that determines the behavior of the job if the step succeeds or fails.
idStep = idStep + 1
oJobStep.Name = JobID & idStep
oJobStep.StepID = idStep
oJobStep.SubSystem = "TSQL"
The subsystem property specifies the SQL Server Agent execution subsystem used to interpret job step task-defining text.
If DatabaseName <> "" Then
oJobStep.DatabaseName = DatabaseName
oJobStep.DatabaseName = "yourdatabase"
If the user fails to pass the database name from the front end, then the component will pick up the hard coded database name, provided that you have hard coded the database name in your code.
If idStep = "1" Then
If CommandText <> "" Then
oJobStep.Command = CommandText
oJobStep.Command = "select * from table1"
oJobStep.OnSuccessAction = SQLDMOJobStepAction_GotoNextStep
oJobStep.StepID = 2
If Commandtext2 <> "" Then
oJobStep.Command = Commandtext2
oJobStep.Command = "delete from table2"
oJobStep.OnSuccessAction = SQLDMOJobStepAction_QuitWithSuccess
We have added two commands to the jobs, one will return all the records from the table and the second will delete all the records from the particular table. This has been done just to give you an example, you can do whatever you want with your database tables by passing the command text either from the front end or by hard coding the command text in the code as seen above.
Add the individual job step to the
applytotargetserver method adds an execution target to the list of targets maintained for the referenced SQL Server Agent job.
Now, here comes the important part, the scheduling of the job, the job has been created but now we have to schedule the job so that it runs at a specific date and time.
JobSchedule object exposes the attributes of a single SQL Server Agent executable job schedule.
Dim oJobSchedule As SQLDMO.JobSchedule
Set oJobSchedule = New SQLDMO.JobSchedule
You can calculate any time and date for your task to start execution, it solely depends on your choice or requirement. We have calculated the year, month, and day separately.
Dim startyear, startmonth, startday
oJobSchedule.Name = JobID
oJobSchedule.Schedule.FrequencyType = SQLDMOFreq_OneTime
We want to execute the task only once, so we have set the frequency type to single time.
mydate = DateAdd("h", CInt(Num_Of_Hours), Now())
Dim hr, min, sec
hr = Hour(mydate)
min = Minute(mydate)
sec = Second(mydate)
mytime = hr & min & sec
startyear = DatePart("yyyy", mydate)
startmonth = DatePart("m", mydate)
startday = DatePart("d", mydate)
If Len(startmonth) < 2 Then startmonth = "0" & startmonth
If Len(startday) < 2 Then startday = "0" & startday
oJobSchedule.Schedule.ActiveStartDate = _
startyear & startmonth & startday
Activestartdate property indicates the first effective date for a schedule.
oJobSchedule.Schedule.ActiveStartTimeOfDay = mytime
Activestarttimeofday property indicates the start time of the day for a schedule.
'Indicate that the schedule never expires
oJobSchedule.Schedule.ActiveEndDate = SQLDMO_NOENDDATE
oJobSchedule.Schedule.ActiveEndTimeOfDay = SQLDMO_NOENDTIME
Similarly, we have to provide the active end date and time for the job. We have set these properties to
SQLDMO_NOENDTIME which means that the job will never expire until it is executed.
Now, here is the clever part, that is, how to remove the task from the scheduler automatically, there is a property named as
DeleteLevel which controls post-execution processing for SQL Server Agent jobs.
oJob.DeleteLevel = SQLDMOComp_Success
If the job is successful then we delete the job from the scheduler.
oJobStep.OnFailAction = SQLDMOJobStepAction_QuitWithFailure
If SQLDMOJobStepAction_QuitWithFailure = True Then
ErrDesc = "Failure"
ErrDesc = "Success"
oJob.StartStepID = 1
Set oJob = Nothing
Set oJobStep = Nothing
Set oJobSchedule = Nothing
Set oJob = Nothing
Set oJobStep = Nothing
Set oJobSchedule = Nothing
ErrDesc = "Failure: " & "'" & Err.Source _
& "'" & " " & Err.Number & " " & Err.Description
Rest of the code is similar to the one we saw in the first part, destroy the object when the class terminates. Compile the DLL and access the component either in your VB project or ASP code. It works fine and efficiently. You can customize the component to add more features or to change the functionality according to your own needs.
There is a difference in SQLOLE and SQLDMO, SQLOLE.DLL library comes with SQL Server 6.5 while SQLDMO.DLL library comes with SQL Server 7.0. You will have to include the correct reference to the library. In the case of this article, add the reference to the SQLDMO.DLL.