Home > Articles > Data > SQL Server

SQL Server Reference Guide

Hosted by

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Design Elements Part 16: Event-Driven Programming

Last updated Mar 28, 2003.

In my article on Event-Driven programming, I covered some simple techniques to have SQL Server respond to an event in code. While these techniques technically meet the definition for event-driven programming, a strict interpretation requires a little more information. Today, I'll explain a set of tools that truly respond to an event.

Recall that event-driven programming is when code responds to a system-generated event, such as a button-push or a clock cycle. While high level languages such as C# or Visual Basic.NET are usually better suited to these kinds of events, there are times when the tools I'll show you today do the job quite nicely.

I'll use three devices to get us there: an alert, a job, and a RAISERROR statement. Let's get started.

Alerts are part of SQL Server's management tools running under SQL Server Agent. This service (and there's one for each instance of SQL Server) uses the msdb database and reads alert messages that are defined in the sysmessages table. When the alert is triggered, it places these messages in the Windows Application Event Log.

The SQL Server Agent monitors the Application log to determine if it should respond. An alert is raised in two ways:

  • Alerts with a level of 20-25 are automatically responded to by SQL Server, and

  • You can create your own user alerts and define custom actions for the response.

These "user" alerts are what we'll focus on today. They are called in code using the RAISERROR statement, which we'll see in a moment. The alert can respond to the message or error number with a SQL Server Job.

These three devices are what I'll use to create a custom response to a condition, which is placed in code, stored procedures, even triggers.

First, let's begin by creating the alert. I open Enterprise Manager, and drill down to Management and then to the Alerts object. I right-click the object and select New Alert.

Figure 124Figure 124

I name the alert "Test", and leave the type set to SQL Server event alert.

NOTE

The other option is to set up an alert based on a Performance Counter object, which we'll explore at another time.

You can set the alert to trigger based on an error number or a severity level. The difference is that an error number is something you create and control, and severity is controlled by SQL Server or you. Severity is also a bit broader, since you can assign several alerts to have the same severity, even if the error numbers are different. This allows you to write one alert for several situations, reserving the error numbers for specific alerts. I'll stick with the error number for this demo.

NOTE

You can further limit the alert by defining text within the message you send during the RAISERROR statement. I'll leave that blank for now.

Notice the ellipses next to the error number. Since this error has never been created for SQL Server before, I have to define it. It's a simple process of selecting the error number, text, and severity to be defined for the error.

At this point you might be wondering, "Why all this talk about errors? I thought we were talking about events!"

SQL Server is fairly weak in regards to error handling, and alerts were created to help out. Since alerts can run code when they respond, and you can set up your own error codes (such I as have done here), you can use them to handle events other than true errors.

Next I set this alert to listen on all databases, but you can restrict it to only respond to errors generated in one particular database, which gives you even more flexibility.

Figure 125Figure 125

Next, I click the Response tab. Here's where we set the code that will run.

Before I do that, notice the "Delay between responses" box at the bottom of the screen. If you don't change the interval to something in the "seconds" range, your job won't fire very often. If your event could be called even more often than that, use the techniques in the previous events article.

Figure 126Figure 126

Now that we have that out of the way, I create a simple job called "Test" by clicking the ellipses next to the Execute Job box.

SQL Server jobs are the second part of the alerting process, but I'll save a full discussion of those for another tutorial. For this demonstration, I'll create a job with one step: it simply inserts the value "Buck" into a table I have with just one column. Your logic would obviously be far more complex (or at least could use your own name).

To create this simple example, only two panels are required: the first panel naming the job and one step in the next tab, with the following code:

Figure 127Figure 127

After I create the job, I return to the Response tab and select OK to finish up.

Since we jumped around a bit, let's take a moment here and diagram what's needed to get to this point:

  1. Create a new Alert, giving it an error number of 50001, which you also create.

  2. Set the alert to run a job, which you also create from within the Response tab.

  3. Return to the Alert object and select OK.

That brings us up to the final step. The alert now lies dormant, and awaits the error number that will cause it to fire. In this step, I'll explain how we'll use the RAISERROR statement.

TIP

You can learn more about RAISERROR from Books Online or in my article on handling errors.

For our purposes here, I use the RAISERROR statement to call up the custom alert I created earlier, which in turn runs the job I created at the same time. Here's the code:

RAISERROR (50001, 1, 1)

The RAISERROR statement is followed by the error number, which I created earlier. This is the important part, since this is the number SQL Server Agent monitors to trigger the alert, which runs the job.

The next number is the severity level. For this number, you can use 0-16 for yourself; the rest SQL Server owns.

The final number is the "state" – which isn't defined very well by Microsoft. You can always just leave it at 1.

Once I run the statement, I can see the results by checking the tracking table.

Of course, this RAISERROR code is quite simple, as is the job and the alert. You can modify the alert to have more information, change the job to have multiple steps and even include looping actions, and add the RAISERROR statement to stored procedures, in-line SQL, and more.

As you're playing with alerts, make sure to use the layering techniques I've been preaching, and make sure that you include true error code – yes, even in the alerts you need to be thinking about what could go wrong!

Online Resources

Having problems with the jobs you're creating for this kind of programming? Check out Database Journal's site for troubleshooting jobs.

InformIT Tutorials and Sample Chapters

Alerts can also respond to events by sending an E-mail. Check out my article on agent and mail.