- Introduction
-
Table of Contents
- Microsoft SQL Server Defined
- Microsoft SQL Server Features
- Microsoft SQL Server Administration
-
Microsoft SQL Server Programming
- An Outline for Development
- Database
- 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
- NULLs
- 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 15: Event-Driven Programming Vs. Scheduled Processes
Last updated Mar 28, 2003.
You can write a program in one of three modes: procedural, event-driven, or scheduled. The procedural method is based on lines of code starting at the top (however that is indicated) and moving to the next indicated line of code.
Back in the old days, a GW-BASIC language program might look something like this:
10 PRINT "Hi there! I will try to guess your name." 20 DIM N$(50) 30 OPEN "I",1,"NAMES.DAT" 40 INPUT #1, A 50 FOR I=1 TO A 60 LINE INPUT #1,N$(I) 70 NEXT I 80 CLOSE 1 90 N$(0)=STR$(A) ...
Even though the code can move to another line of code, it's still a line-by-line interpretation of programming statements.
Procedural code is still very much with us. Even within the other types of code, lines are interpreted one at a time.
In event-driven code, sections of program code are divided into subroutines or classes. The program doesn't do anything unless some event tells it to do so (such as the user pressing a key or a mouse button). Often, there is a main event, such as opening the first form or a "main" class. These events can kick-off the procedural code inside. Languages including Visual Basic, Java, and C++ are all event-driven.
Strictly speaking, scheduled code is also event-driven, but it's treated differently since the event is always the same: the clock. This kind of programming is sometimes called "batch mode," especially in mainframe and enterprise environments. Scheduled code uses the computer's built-in clock circuitry to order its events.
T-SQL is a bit of all three. SQL Server interprets each line of T-SQL code one at a time. In that way, it's procedural. But SQL Server also has the facilities to respond to events, and one of those events is also a scheduler. In those aspects, SQL Server can be event driven or scheduled.
Today, I'll examine some of the tools you can use to have your system run bits of code based on an event. I'll develop these concepts further in my next article as well, when I'll also cover scheduled programming.
The first tool at our disposal is the trigger. I covered the database trigger in another article, but the long and short of it is that a trigger is a set of code that runs whenever data is added, deleted, or updated in a table.
These types of triggers are certainly the right choice if the event you're looking to respond to is one of those activities. If the event is data related, an instead-of trigger is more useful. (The instead-of trigger defers the insert, update, or delete and instead only runs the code in the trigger.)
Triggers are certainly invaluable in database operations, but when I think of event-level programming, triggers aren't always what I have in mind. Instead of depending on a data event, I want to run another set of code from whichever code I'm currently running.
Stored procedures allow "calling" another stored procedure from within its code. Strictly speaking, this is still procedural code but since it responds to events that other stored procedures create, we can count it as event-driven.
I'll illustrate this concept with a very simple example. Below you'll find two stored procedures. The first (test1) accepts a single variable: the last name of an author. With that information, this first stored procedure looks up the state that the author lives in.
The test1 procedure then calls another (test2) that uses the output of test1 to find all the authors that live in the same state.
It would be a very simple matter to write this code as a single query, but I'm keeping it simple so that we concentrate on understanding how one stored procedure calls another.
Here's stored procedure number one:
CREATE PROCEDURE test1 (@LastName varchar(30)) AS DECLARE @State varchar(2) SELECT @State = state FROM authors WHERE au_lname LIKE @LastName EXEC test2 @State GO
The first line of the stored procedure sets up the input variable (@LastName). In the third line, I declared a variable to hold the result of a query to get the author's state. That variable is passed to another stored procedure in the seventh line. Here's the "called" stored procedure which returns the final results:
CREATE PROCEDURE test2 (@StateName varchar(2)) AS SELECT au_fname + ' ' + au_lname, state FROM authors WHERE state LIKE @StateName GO The following query makes use of these two stored procedures: EXEC test1 'White' GO ---------------------------
Johnson White |
CA |
Marjorie Green |
CA |
Cheryl Carson |
CA |
Michael O'Leary |
CA |
Dean Straight |
CA |
Abraham Bennet |
CA |
Ann Dull |
CA |
Burt Gringlesby |
CA |
Charlene Locksley |
CA |
Akiko Yokomoto |
CA |
Dirk Stringer |
CA |
Stearns MacFeather |
CA |
Livia Karsen |
CA |
Sheryl Hunter |
CA |
Heather McBadden |
CA |
This is quite a trivial example, but it does the trick. In database programming parlance, this is called a "nested stored procedure", since one stored procedure is called from another.
You can "nest" these stored procedures up to 32 levels deep. You can find out where you are with this command:
SELECT @@NESTLEVEL
To be stricter about the definition of event-level programming, the system needs to "listen" for events to occur and then respond to them. SQL Server does provide a means for that type of behavior in T-SQL by "alerts" and "jobs." (Next week I'll focus more on those objects and how you can use them to wire up some fairly complex event logic.)
In the articles on SQL Server programming, I haven't covered programming against SQL Server's object model using other languages. This model is available by including or referencing the SQL Server libraries or DLLs in code such as Visual Basic or C#. That type of programming is covered elsewhere at InformIT. Other authors explain this type of programming, which has inherent support for true object oriented and event-level programming. Check out the .NET articles by Jim Mischel, C++ by Danny Kalev, and Java by Steven Haines. Several other articles and books are available at InformIT that explain programming with other languages and platforms.
Online Resources
John Papa has a great article on Microsoft's MSDN site regarding SQL Server triggers.
InformIT Tutorials and Sample Chapters
Dan Fox has a good book on Safari that covers Visual Basic programming and events.
