Table of Contents
- Microsoft SQL Server Defined
- Microsoft SQL Server Features
- Microsoft SQL Server Administration
Microsoft SQL Server Programming
- An Outline for Development
- Database Services
- Database Objects: Databases
- Database Objects: Tables
- Database Objects: Table Relationships
- Database Objects: Keys
- Database Objects: Constraints
- Database Objects: Data Types
- Database Objects: Views
- Database Objects: Stored Procedures
- Database Objects: Indexes
- Database Objects: User Defined Functions
- Database Objects: Triggers
- Database Design: Requirements, Entities, and Attributes
- Business Process Model Notation (BPMN) and the Data Professional
- Business Questions for Database Design, Part One
- Business Questions for Database Design, Part Two
- Database Design: Finalizing Requirements and Defining Relationships
- Database Design: Creating an Entity Relationship Diagram
- Database Design: The Logical ERD
- Database Design: Adjusting The Model
- Database Design: Normalizing the Model
- Creating The Physical Model
- Database Design: Changing Attributes to Columns
- Database Design: Creating The Physical Database
- Database Design Example: Curriculum Vitae
- The SQL Server Sample Databases
- The SQL Server Sample Databases: pubs
- The SQL Server Sample Databases: NorthWind
- The SQL Server Sample Databases: AdventureWorks
- The SQL Server Sample Databases: Adventureworks Derivatives
- UniversalDB: The Demo and Testing Database, Part 1
- UniversalDB: The Demo and Testing Database, Part 2
- UniversalDB: The Demo and Testing Database, Part 3
- UniversalDB: The Demo and Testing Database, Part 4
- Getting Started with Transact-SQL
- Transact-SQL: Data Definition Language (DDL) Basics
- Transact-SQL: Limiting Results
- Transact-SQL: More Operators
- Transact-SQL: Ordering and Aggregating Data
- Transact-SQL: Subqueries
- Transact-SQL: Joins
- Transact-SQL: Complex Joins - Building a View with Multiple JOINs
- Transact-SQL: Inserts, Updates, and Deletes
- An Introduction to the CLR in SQL Server 2005
- Design Elements Part 1: Programming Flow Overview, Code Format and Commenting your Code
- Design Elements Part 2: Controlling SQL's Scope
- Design Elements Part 3: Error Handling
- Design Elements Part 4: Variables
- Design Elements Part 5: Where Does The Code Live?
- Design Elements Part 6: Math Operators and Functions
- Design Elements Part 7: Statistical Functions
- Design Elements Part 8: Summarization Statistical Algorithms
- Design Elements Part 9:Representing Data with Statistical Algorithms
- Design Elements Part 10: Interpreting the Data—Regression
- Design Elements Part 11: String Manipulation
- Design Elements Part 12: Loops
- Design Elements Part 13: Recursion
- Design Elements Part 14: Arrays
- Design Elements Part 15: Event-Driven Programming Vs. Scheduled Processes
- Design Elements Part 16: Event-Driven Programming
- Design Elements Part 17: Program Flow
- Forming Queries Part 1: Design
- Forming Queries Part 2: Query Basics
- Forming Queries Part 3: Query Optimization
- Forming Queries Part 4: SET Options
- Forming Queries Part 5: Table Optimization Hints
- Using SQL Server Templates
- Transact-SQL Unit Testing
- Index Tuning Wizard
- Unicode and SQL Server
- SQL Server Development Tools
- The SQL Server Transact-SQL Debugger
- The Transact-SQL Debugger, Part 2
- Basic Troubleshooting for Transact-SQL Code
- An Introduction to Spatial Data in SQL Server 2008
- Performance Tuning
- Practical Applications
- Professional Development
- Application Architecture Assessments
- Business Intelligence
- Tips and Troubleshooting
- Additional Resources
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.
I name the alert "Test", and leave the type set to SQL Server event alert.
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.
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.
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.
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:
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:
Create a new Alert, giving it an error number of 50001, which you also create.
Set the alert to run a job, which you also create from within the Response tab.
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.
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!
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.