The WORK_AddWorkTransaction Stored Procedure

The WORK_AddWorkTransaction Stored Procedure

Figure 7-33 shows a stored procedure that records the acquisition of a work in the View Ridge database. Again, this code is generic, but the code style in Figure 7-33 is closer to that used in SQL Server T-SQL rather than the Oracle PL/SQL style that was used for the trigger examples in the prior section. If you compare the pseudocode examples in both sections, you can gain a sense of the differences between code written in PL/SQL and T-SQL.

The WORK_addWorkTransaction procedure receives five input parameters and returns none. In a more realistic example, a return parameter would be passed back to the caller to indicate the success or failure of the operation. That discussion takes us away from database concepts, however, and we will omit it here. This code does not assume that the value of ArtistID that is passed to it is a valid ID. Instead, the first step in the stored procedure is to check whether the ArtistID value is valid. To do this, the first block of statements counts the number of rows that have the given ArtistID value. If the count is zero, then the ArtistID value is invalid, and the procedure writes an error message and returns.

Otherwise, 3 the procedure then checks to determine if the work has been in the View Ridge Gallery before. If so, the WORK table will already contain a row for this ArtistID, Title,

Figure 7-32

• Greater security • Decreased network traffic

Advantages of Stored

• SQL can be optimized

Procedures

• Code sharing

• Less work • Standardized processing • Specialization among developers

3 This code does not check for more than one row having the given ArtistID, because ArtistID is a surrogate key.

Figure 7-33

Stored Procedure to Record the Acquisition of a Work

Part 3 Database Implementation

and Copy. If no such row exists, the procedure creates a new WORK row. Once that has been done, it then uses a SELECT to obtain a value for the WorkID value. If the WORK row was just created, this statement is necessary to obtain the new value of the WorkID surrogate key. If the work was not created, the SELECT on WorkID is necessary to obtain the WorkID of the existing row. Once a value of WorkID has been obtained, the new row is inserted into TRANS. Notice that the system function GetDate() is used to supply a value for DateAcquired in the new row.

This procedure illustrates how SQL is embedded in stored procedures. It is not complete, because we need to do something to ensure that either all updates are made to the database or none of them are. You will learn how to do this in Chapter 9. For now, just concentrate on how SQL can be used as part of a database application.

SQL DDL statements are used to manage the structure of define views. The only restriction is that a view definition tables. This chapter presented three SQL DDL statements:

may not include an ORDER BY clause. CREATE TABLE, ALTER TABLE, DROP TABLE, and TRUN-

Views are used to hide columns or rows and to show the CATE TABLE. SQL is preferred over graphical tools for creat-

results of computed columns. They also can hide complicated ing tables because it is faster, it can be used to create the

SQL syntax, such as that used for joins and GROUP BY same table repeatedly, tables can be created from program

queries, and layer computations and built-in functions so that code, and it is standardized and DBMS independent.

computations can be used in WHERE clauses. Some organiza- The IDENTITY (N, M) data type is used to create

tions use views to provide table aliases. Views also can be used surrogate key columns, where N is the starting value and M is

to assign different sets of processing permissions to tables and the increment to be added. The SQL CREATE TABLE state-

to assign different sets of triggers as well. The rules for deter- ment is used to define the name of the table, its columns, and

mining whether a view can be updated are both complicated constraints on columns. There are five types of constraints:

and DBMS specific. Guidelines are shown in Figure 7-23. PRIMARY KEY, UNIQUE, NULL/NOT NULL, FOREIGN KEY,

SQL statements can be embedded in program code in and CHECK.

functions, triggers, stored procedures, and application code. The purposes of the first three constraints are obvious.

To do so, there must be a way to associate SQL table columns FOREIGN KEY is used to create referential integrity constraints;

with program variables. Also, there is a paradigm mismatch CHECK is used to create data constraints. Figure 7-11 summa-

between SQL and programs. Most SQL statements return rizes techniques for creating relationships using SQL constraints.

sets of rows; an application expects to work on one row at a Simple default values can be assigned using the

time. To resolve this mismatch, the results of SQL state- DEFAULT keyword. Data constraints are defined using

ments are processed as pseudofiles using a cursor. Web data- CHECK constraints. Domain, range, and intratable con-

base applications are a good example of SQL statements straints can be defined. Although SQL-92 defined facilities

embedding in application program code. for interrelation CHECK constraints, those facilities were

SQL/PSM is the portion of the SQL standard that not implemented by DBMS vendors. Instead, interrelation

provides for storing reusable modules of program code within constraints are enforced using triggers.

a database. SQL/PSM specifies that SQL statements will be The ALTER statement is used to add and remove

embedded in functions, triggers, and stored procedures in a columns and constraints. The DROP statement is used to

database. It also specifies SQL variables, cursors, control- drop tables. In SQL DDL, parents need to be created first and

of-flow statements, and output procedures. dropped last.

A trigger is a stored program that is executed by the DBMS The DML SQL statements are INSERT, UPDATE,

whenever a specified event occurs on a specified table or view. DELETE, and MERGE. Each statement can be used on a single

In Oracle, triggers can be written in Java or in a proprietary row, on a group of rows, or on the entire table. Because of their

Oracle language called PL/SQL. In SQL Server, triggers can be power, both UPDATE and DELETE need to be used with care.

written in a propriety SQL Server language called TRANSACT- Some people believe the JOIN ON syntax is an easier

SQL, or T-SQL, and in Microsoft CLR languages, such as Visual form of join. Rows that have no match in the join condition

Basic.NET, C# .NET, and C++ .NET. With MySQL, triggers can are dropped from the join results. To keep such rows, use a

be written in MySQL’s variant of SQL. LEFT OUTER or RIGHT OUTER join rather than a regular,

Possible triggers are BEFORE, INSTEAD OF, and AFTER. or INNER, join.

Each type of trigger can be declared for insert, update, and An SQL view is a virtual table that is constructed from

delete actions, so nine types of triggers are possible. Oracle other tables and views. SQL SELECT statements are used to

supports all nine trigger types, SQL Server supports only

Chapter 7 SQL for Database Construction and Application Processing

INSTEAD OF and AFTER triggers, and MySQL supports the BEFORE and AFTER triggers. When a trigger is fired, the DBMS supplies old and new values for the update. New values are provided for inserts and updates, and old values are provided for updates and deletions. How these values are provided to the trigger depends on the DBMS in use.

Triggers have many uses. This chapter discussed four: set- ting default values, enforcing interrelation data constraints, updating views, and enforcing referential integrity actions.

A stored procedure is a program that is stored within the database and compiled when used. Stored procedures can receive input parameters and return results. Unlike trig- gers, their scope is database-wide; they can be used by any process that has permission to run the stored procedure.

Stored procedures can be called from programs written in the same languages used for triggers. They also can be called from DBMS SQL utilities. The advantages of using stored procedures are summarized in Figure 7-32.

casual relationship CHECK constraint cursor data definition language (DDL) data manipulation language (DML) DEFAULT keyword FOREIGN KEY constraint IDENTITY({StartValue}, {Increment}) property inner join interrelation constraint intrarelation constraint NOT NULL constraint NULL constraint PRIMARY KEY constraint procedural programming language Procedural Language/SQL (PL/SQL) pseudofile SQL/Persistent Stored Modules (SQL/PSM) SQL ADD clause SQL ADD CONSTRAINT clause SQL ALTER TABLE statement SQL ALTER VIEW statement SQL AS keyword SQL CREATE TABLE statement

SQL CREATE VIEW statement SQL DELETE statement SQL DROP COLUMN clause SQL DROP CONSTRAINT clause SQL DROP TABLE statement SQL INSERT statement SQL JOIN ON syntax SQL LEFT JOIN syntax SQL left outer join SQL MERGE statement SQL ON DELETE clause SQL ON UPDATE clause SQL outer join SQL RIGHT JOIN syntax SQL right outer join SQL TOP {NumberOfRows} syntax SQL TRUNCATE TABLE statement SQL UPDATE statement SQL view stored procedure Transact-SQL (T-SQL) trigger UNIQUE constraint

7.1 What does DDL stand for? List the SQL DDL statements.

7.2 What do es DML stand for? List the SQL DML statements.

7.3 Explain the meaning of the following expression: IDENTITY (4000, 5).

For this set of Review Questions, we will create and use a database for the Review Wedgewood Pacific Corporation (WPC) that is similar to the Microsoft Access database we created and used in Chapters 1 and 2. Founded in 1957 in Seattle, Washington, WPC has grown into an internationally recognized organization. The company is located in two buildings. One building houses the Administration, Accounting, Finance, and Human Resources departments, and the second houses the

Part 3 Database Implementation

Production, Marketing, and Information Systems departments. The company database contains data about employees; departments; projects; assets, such as computer equipment; and other aspects of company operations.

The database will be named WPC and will contain the following four tables:

DEPARTMENT (DepartmentName, BudgetCode, OfficeNumber, Phone) EMPLOYEE (EmployeeNumber, FirstName, LastName, Department, Phone, Email) PROJECT (ProjectID, Name, Department, MaxHours, StartDate, EndDate) ASSIGNMENT (ProjectID, EmployeeNumber, HoursWorked)

EmployeeNumber is a surrogate key that starts at 1 and increments by 1. ProjectID is a surrogate key that starts at 1000 and increases by 100. DepartmentName is the text name of the department, and is therefore not a surrogate key.

The WPC database has the following referential integrity constraints:

Department in EMPLOYEE must exist in Department in DEPARTMENT Department in PROJECT must exist in Department in DEPARTMENT ProjectID in ASSIGNMENT must exist in ProjectID in PROJECT EmployeeNumber in ASSIGNMENT must exist in EmployeeNumber in EMPLOYEE

The relationship from EMPLOYEE to ASSIGNMENT is 1:N, M-O and the relationship from PROJECT to ASSIGNMENT is 1:N, M-O. The database also has the following business rules:

• If an EMPLOYEE row is to be deleted and that row is connected to any

ASSIGNMENT, the EMPLOYEE row deletion will be disallowed. • If a PROJECT row is deleted, then all the ASSIGNMENT rows that are connected to

the deleted PROJECT row will also be deleted.

The business sense of these rules is as follows: