prentice hall © 20041 cos 346 day 16. 7-2 agenda questions?questions? assignment 6...

51
Prentice Hall © 2004 1 COS 346 COS 346 Day 16 Day 16

Post on 20-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 1

COS 346COS 346

Day 16Day 16

Page 2: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

7-2

AgendaAgenda

• Questions?Questions?• Assignment 6 Corrected Assignment 6 Corrected

– 7 A’s and 1 late assignment 7 A’s and 1 late assignment • Assignment 7 DueAssignment 7 Due• Assignment 8 posted Assignment 8 posted

– Due April 6 Due April 6 • New Time line New Time line • More on SQL & SQL ServerMore on SQL & SQL Server

– Chap 10 Stored Procedures and TriggersChap 10 Stored Procedures and Triggers• We will be in the other text next classWe will be in the other text next class

– Chap 8 Chap 8

Page 3: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

New time lineNew time line

• MarchMarch

– 30 - SQL 1030 - SQL 10

• Assignment 7 dueAssignment 7 due

• Progress reportProgress report

• AprilApril

– 2 Database Redesign 2 Database Redesign – 6 - 6 - Database redesign Database redesign

• Quiz 2Quiz 2

• Assignment 8 due Assignment 8 due

– 9 - Managing Multiuser databases 9 - Managing Multiuser databases

– 13 - Managing Multiuser databases 13 - Managing Multiuser databases

• Assignment 9 due Assignment 9 due

– 16 Managing Multiuser databases 16 Managing Multiuser databases

– 20 Database access standards20 Database access standards

• Progress report Progress report

– 23 - Database access standards23 - Database access standards

• Assignment 10 dueAssignment 10 due

– 2727

• Quiz 3Quiz 3

• Capstones Presentations Due Capstones Presentations Due

Page 4: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 4

Chapter 10: Stored Procedures and Chapter 10: Stored Procedures and TriggersTriggers

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 5: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 5

ObjectivesObjectives

• Learn the advantages of stored procedures.Learn the advantages of stored procedures.• Learn about the permissions required to create stored Learn about the permissions required to create stored

procedures.procedures.• Create and execute stored procedures.Create and execute stored procedures.• Write stored procedures with multiple parameters.Write stored procedures with multiple parameters.• Learn to avoid stored procedure parameter errors.Learn to avoid stored procedure parameter errors.• Drop stored procedures.Drop stored procedures.• Learn how triggers work.Learn how triggers work.• Learn the different types of triggers. Learn the different types of triggers. • Write program code to create AFTER and INSTEAD OF Write program code to create AFTER and INSTEAD OF

triggers.triggers.• Define the order of trigger execution for tables with Define the order of trigger execution for tables with

multiple triggers. multiple triggers.

Page 6: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 6

• A A stored procedurestored procedure is a kind of computer is a kind of computer program to process tasks that are program to process tasks that are repetitive in nature—meaning these repetitive in nature—meaning these computerized tasks are conducted over computerized tasks are conducted over and over during the course of business. and over during the course of business.

• Example: a procedure to process salary Example: a procedure to process salary increases for employees of an increases for employees of an organization.organization.

Stored ProceduresStored Procedures

Page 7: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 7

Advantages of Stored ProceduresAdvantages of Stored Procedures

• The ability to automate repetitive tasks. The ability to automate repetitive tasks. • The ability to call a stored procedure from an The ability to call a stored procedure from an

application program written in another application program written in another programming language such as Visual Basic.NET programming language such as Visual Basic.NET and Visual C++. and Visual C++.

• Efficiency—SQL Server will generate and Efficiency—SQL Server will generate and maintain (store) an execution plan for a stored maintain (store) an execution plan for a stored procedure—thus, the stored procedure will procedure—thus, the stored procedure will execute very efficiently. execute very efficiently.

• Security—you can grant permission to execute Security—you can grant permission to execute stored procedures that modify database objects stored procedures that modify database objects such as tables without granting explicit permission such as tables without granting explicit permission to modify the database objects directly. to modify the database objects directly.

Page 8: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 8

Permission to Create ProceduresPermission to Create Procedures

• Procedures are created by executing the Procedures are created by executing the CREATE PROCEDURE statement. CREATE PROCEDURE statement.

• The statement can be abbreviated to The statement can be abbreviated to CREATE PROC.CREATE PROC.

• A Database Administrator must grant you A Database Administrator must grant you the permission to execute the CREATE the permission to execute the CREATE PROCEDURE statement.PROCEDURE statement.

Page 9: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 9

CREATE PROCEDURE SyntaxCREATE PROCEDURE SyntaxCREATE PROCEDURE [owner.]procedure_name [(@parameter1 datatype1 CREATE PROCEDURE [owner.]procedure_name [(@parameter1 datatype1 [=DEFAULT], [{@parameter2 datatype2 [= DEFAULT], . . .})] [=DEFAULT], [{@parameter2 datatype2 [= DEFAULT], . . .})] AS {INSERT | UPDATE | DELELTE} table_nameAS {INSERT | UPDATE | DELELTE} table_name {code to execute for the procedure}{code to execute for the procedure}

• The The ownerowner of a procedure is the system user account which is of a procedure is the system user account which is assigned ownership through this particular option. Often assigned ownership through this particular option. Often ownership is assigned to a system user who works as a DBA.ownership is assigned to a system user who works as a DBA.

• Procedure parameters are optional (@parameter1, @parameter2, Procedure parameters are optional (@parameter1, @parameter2, …) enclosed within parentheses of specified data types …) enclosed within parentheses of specified data types (datatype1, datatype2, …). (datatype1, datatype2, …).

• Parameter names and data types are paired and multiple Parameter names and data types are paired and multiple parameter and data type pairs are separated by commas. parameter and data type pairs are separated by commas. Parameters may or may not be assigned default values.Parameters may or may not be assigned default values.

• Parameters are used to pass values to the stored procedure—they Parameters are used to pass values to the stored procedure—they can also pass values back to a calling procedure. can also pass values back to a calling procedure.

Page 10: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 10

Stored Procedure Example #1—Pay RaiseStored Procedure Example #1—Pay Raise

• This procedure receives the percent value of the raise to be This procedure receives the percent value of the raise to be assigned through the parameter named @percent_raise. assigned through the parameter named @percent_raise.

• The default value is 3%, any percentage raise can be passed to The default value is 3%, any percentage raise can be passed to the stored procedure. the stored procedure.

CREATE PROCEDURE pay_raise (@percent_raise CREATE PROCEDURE pay_raise (@percent_raise DECIMAL(3,1)=3.0) AS UPDATE employee DECIMAL(3,1)=3.0) AS UPDATE employee

SET emp_salary = emp_salary + SET emp_salary = emp_salary + (emp_salary * @percent_raise/100);(emp_salary * @percent_raise/100);

• This is an UPDATE procedure that will update each employee This is an UPDATE procedure that will update each employee record by increasing the salary through the SET clause. record by increasing the salary through the SET clause.

Page 11: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 11

Creating Stored Procedure #1 Creating Stored Procedure #1 Using Query AnalyzerUsing Query Analyzer

Page 12: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 12

• Stored procedures can be executed with the SQL Query Stored procedures can be executed with the SQL Query Analyzer through use of the EXECUTE statement. This Analyzer through use of the EXECUTE statement. This statement may be abbreviated as EXEC. The simplified, statement may be abbreviated as EXEC. The simplified, general syntax of the EXEC statement is:general syntax of the EXEC statement is:

EXEC procedure_name [(@parameter1=value1 EXEC procedure_name [(@parameter1=value1

{, @parameter2=value2, …})]{, @parameter2=value2, …})]

• Here is an example of executing the stored procedure Here is an example of executing the stored procedure named named pay_raisepay_raise..

EXEC pay_raise 7.5EXEC pay_raise 7.5

(8 row(s) affected) (8 row(s) affected)

Executing Stored Procedure #1Executing Stored Procedure #1

Page 13: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 13

Results from Executing Stored Procedure #1Results from Executing Stored Procedure #1

• SQL Example 10.4 executes a SELECT statement to show SQL Example 10.4 executes a SELECT statement to show the new salary levels. The procedure raised all employee the new salary levels. The procedure raised all employee salaries by 7.5%.salaries by 7.5%.

SELECT emp_ssn "SSN", emp_last_name "Last Name", SELECT emp_ssn "SSN", emp_last_name "Last Name", CONVERT (CHAR (10), emp_salary, 1) "Salary" CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employeeFROM employeeORDER BY emp_ssn;ORDER BY emp_ssn;SSN Last Name Salary SSN Last Name Salary --------- ------------------------- ---------- --------- ------------------------- ---------- 999111111 Bock 32,250.00999111111 Bock 32,250.00999222222 Amin 26,875.00999222222 Amin 26,875.00999333333 Joshi 40,850.00999333333 Joshi 40,850.00more rows will display …more rows will display …

Page 14: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 14

Stored Procedure Example #2—Individual RaiseStored Procedure Example #2—Individual Raise

• As an alternative to a stored procedure that As an alternative to a stored procedure that provides provides allall employees with a raise, this stored employees with a raise, this stored procedure is designed to enable the application of procedure is designed to enable the application of percentage raises for percentage raises for individualindividual employees. employees.

• This procedure takes two input parameter values: This procedure takes two input parameter values: (1) the employee social security number (1) the employee social security number ((@emp_ssn@emp_ssn), and (2) percent of raise ), and (2) percent of raise

((@percent_raise@percent_raise).). • The SSN is CHAR data while the percent raise is The SSN is CHAR data while the percent raise is

DECIMAL data.DECIMAL data.

Page 15: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 15

Stored Procedure Example #2—Individual Raise Stored Procedure Example #2—Individual Raise Contd. Contd.

Procedure CodeProcedure Code

• The procedure displays the information on the employee before The procedure displays the information on the employee before and after the raise.and after the raise.

CREATE PROCEDURE individual_raise (@emp_ssn CHAR(9), CREATE PROCEDURE individual_raise (@emp_ssn CHAR(9), @percent_raise DECIMAL(3,1))@percent_raise DECIMAL(3,1)) AS SELECT emp_ssn "SSN", emp_last_name "Last Name", AS SELECT emp_ssn "SSN", emp_last_name "Last Name", CONVERT (CHAR (10), emp_salary, CONVERT (CHAR (10), emp_salary, 11) "Old Salary" ) "Old Salary" FROM employee WHERE emp_ssn = @emp_ssnFROM employee WHERE emp_ssn = @emp_ssn UPDATE employeeUPDATE employee SET emp_salary = emp_salary + SET emp_salary = emp_salary + (emp_salary * @percent_raise/100)(emp_salary * @percent_raise/100) WHERE emp_ssn = @emp_ssnWHERE emp_ssn = @emp_ssn SELECT emp_ssn "SSN", emp_last_name "Last Name", SELECT emp_ssn "SSN", emp_last_name "Last Name", CONVERT (CHAR (10), emp_salary, CONVERT (CHAR (10), emp_salary, 11) "New Salary" ) "New Salary" FROM employee WHERE emp_ssn = @emp_ssn; FROM employee WHERE emp_ssn = @emp_ssn;

Page 16: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 16

Stored Procedure Example #2—Individual Raise Stored Procedure Example #2—Individual Raise Contd.Contd.

Output ResultsOutput Results

EXEC individual_raise @emp_ssn=999555555, EXEC individual_raise @emp_ssn=999555555, @percent_raise=10.0@percent_raise=10.0

SSN Last Name Old Salary SSN Last Name Old Salary --------- ------------------------- ---------- --------- ------------------------- ---------- 999555555 Joyner 46,225.00999555555 Joyner 46,225.00(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)SSN Last Name New Salary SSN Last Name New Salary --------- ------------------------- ---------- --------- ------------------------- ---------- 999555555 Joyner 50,847.50999555555 Joyner 50,847.50(1 row(s) affected)(1 row(s) affected)

Page 17: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 17

The DEFAULT Parameter OptionThe DEFAULT Parameter Option

• A A default parameterdefault parameter value is the value value is the value used by a stored procedure when a used by a stored procedure when a parameter value is parameter value is notnot supplied. supplied.

• The default is optional and when specified, The default is optional and when specified, is set as is shown here.is set as is shown here.

CREATE PROCEDURE pay_raise CREATE PROCEDURE pay_raise (@percent_raise DECIMAL(3,1)(@percent_raise DECIMAL(3,1)=3.0=3.0))

• This EXEC causes the percent raise to be 3.0% This EXEC causes the percent raise to be 3.0% by default.by default.

EXEC pay_raiseEXEC pay_raise

Page 18: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 18

Stored Procedure Parameter ErrorsStored Procedure Parameter Errors

• Errors arise for several reasons such as:Errors arise for several reasons such as:• Attempting to pass parameter values of the incorrect data Attempting to pass parameter values of the incorrect data

typetype• Failing to pass required parameter values so that the Failing to pass required parameter values so that the

procedure cannot execute properly.procedure cannot execute properly.• SQL Example 10.8 shows an attempt to execute the SQL Example 10.8 shows an attempt to execute the

individual_raiseindividual_raise procedure without specifying the required procedure without specifying the required percent amount of the raise.percent amount of the raise.

EXEC individual_raise @emp_ssn=999666666EXEC individual_raise @emp_ssn=999666666Server: Msg 201, Level 16, State 3, Procedure Server: Msg 201, Level 16, State 3, Procedure

individual_raise, Line 0 Procedure individual_raise, Line 0 Procedure 'individual_raise' expects parameter 'individual_raise' expects parameter '@percent_raise', which was not supplied.'@percent_raise', which was not supplied.

Page 19: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 19

Stored Procedure Parameter Errors Contd. Stored Procedure Parameter Errors Contd.

• Here is an attempt to execute the Here is an attempt to execute the individual_raiseindividual_raise procedure by specifying the social security number and procedure by specifying the social security number and percentage of raise in reverse order without specifying the percentage of raise in reverse order without specifying the names of the parameters names of the parameters

• SQL Server generates an error message indicating that the SQL Server generates an error message indicating that the data type data type intint could not be converted to could not be converted to decimaldecimal (those data (those data types expected by the procedure).types expected by the procedure).

EXEC individual_raise 7.5, 999666666EXEC individual_raise 7.5, 999666666

Server: Msg 8114, Level 16, State 1, Procedure Server: Msg 8114, Level 16, State 1, Procedure individual_raise, Line 0individual_raise, Line 0

Error converting data type int to decimal.Error converting data type int to decimal.

Page 20: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 20

Dropping Stored ProceduresDropping Stored Procedures

• Stored procedures are dropped with the Stored procedures are dropped with the DROP PROCEDURE statement. DROP PROCEDURE statement.

• To drop a stored procedure, you must be the To drop a stored procedure, you must be the owner of the procedure, or a DBA with the owner of the procedure, or a DBA with the db_ownerdb_owner or or sysadminsysadmin role permissions. role permissions.

DROP PROCEDURE pay_raise;DROP PROCEDURE pay_raise;

The command(s) completed successfully.The command(s) completed successfully.

Page 21: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 21

TriggersTriggers • TriggersTriggers are program code objects in a are program code objects in a

database that are invoked whenever a database that are invoked whenever a specific action occurs to a table. specific action occurs to a table.

• With early database management systems, With early database management systems, computer scientists referred to the computer scientists referred to the firingfiring of of a trigger; hence the adoption and continued a trigger; hence the adoption and continued use of the term trigger. use of the term trigger.

• Triggers can be invoked by any action that Triggers can be invoked by any action that insertsinserts rows into a table, rows into a table, updatesupdates existing existing table rows, or table rows, or deletesdeletes table rows. table rows.

Page 22: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 22

Triggers (cont.)Triggers (cont.)

• Modern DBMS products like SQL Server use triggers to Modern DBMS products like SQL Server use triggers to enforce a new type of constraint termed a PROCEDURAL enforce a new type of constraint termed a PROCEDURAL INTEGRITY constraint. INTEGRITY constraint.

• This means that triggers enforce what business managers This means that triggers enforce what business managers refer to as refer to as business rulesbusiness rules. .

• For example, the Company may have a policy (business For example, the Company may have a policy (business rule) that employees cannot receive a raise that exceeds rule) that employees cannot receive a raise that exceeds 20% of their current salary level. 20% of their current salary level.

• You have permission to create a trigger for a specific table You have permission to create a trigger for a specific table if you are the owner of the table. A system user with an if you are the owner of the table. A system user with an account that is designated as a data definition language account that is designated as a data definition language administrator or a database owner can also create a trigger administrator or a database owner can also create a trigger for a table.for a table.

Page 23: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 23

Trigger SyntaxTrigger Syntax

• Triggers have four components: (1) the trigger Triggers have four components: (1) the trigger name, (2) the table or view name to which the name, (2) the table or view name to which the trigger is assigned, (3) the timing of the trigger trigger is assigned, (3) the timing of the trigger action and associated DML action, and (4) the action and associated DML action, and (4) the program code to be executed. program code to be executed.

• The simplified, general syntax of the CREATE The simplified, general syntax of the CREATE TRIGGER statement is shown here:TRIGGER statement is shown here:

CREATE TRIGGER trigger_name ON CREATE TRIGGER trigger_name ON {table_name | view_name }{table_name | view_name } {FOR | AFTER | INSTEAD OF } {FOR | AFTER | INSTEAD OF } {[INSERT,] [UPDATE,] [DELETE]}{[INSERT,] [UPDATE,] [DELETE]} AS {batch code | IF UPDATEAS {batch code | IF UPDATE (column_name)}(column_name)}

Page 24: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 24

Trigger Syntax (Cont.)Trigger Syntax (Cont.)• Trigger_nameTrigger_name is the name of the trigger as a database object. is the name of the trigger as a database object. • The table or view for a trigger is specified with the ON clause. The table or view for a trigger is specified with the ON clause. • FOR, AFTER, and INSTEAD OF options define when a trigger FOR, AFTER, and INSTEAD OF options define when a trigger

acts. acts. – FOR and AFTER clauses both specify that a trigger fires FOR and AFTER clauses both specify that a trigger fires

after the event that triggers the firing – AFTER and FOR are after the event that triggers the firing – AFTER and FOR are synonymous.synonymous.

– INSTEAD OF specifies that a trigger should execute instead INSTEAD OF specifies that a trigger should execute instead of the event that would normally activate (fire) the trigger. of the event that would normally activate (fire) the trigger. AFTER triggers are only supported on tables, not views. AFTER triggers are only supported on tables, not views.

• INSERT, UPDATE, and DELETE statements specify which INSERT, UPDATE, and DELETE statements specify which DML event will cause a trigger to fire – DML options can be DML event will cause a trigger to fire – DML options can be combined, but you cannot specify a DELETE statement option combined, but you cannot specify a DELETE statement option for a trigger with an IF UPDATE clause. for a trigger with an IF UPDATE clause.

• The AS clause is used to specify whether the trigger executes: The AS clause is used to specify whether the trigger executes: procedural and nonprocedural T-SQL statements or an IF procedural and nonprocedural T-SQL statements or an IF UPDATE clause. UPDATE clause.

Page 25: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 25

Trigger Example #1—Updating Employee SalaryTrigger Example #1—Updating Employee Salary

• This example uses an audit trail table to store This example uses an audit trail table to store information about changes made to employee information about changes made to employee salary data.salary data.

Audit_Employee Table StructureAudit_Employee Table StructureColumn NameColumn Name Column Data Type and SizeColumn Data Type and Size

emp_ssnemp_ssn CHAR(9)CHAR(9)

old_salaryold_salary MONEYMONEY

new_salarynew_salary MONEYMONEY

system_user_namesystem_user_name CHAR(20)CHAR(20)

datetime_changeddatetime_changed DATETIMEDATETIME

Page 26: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 26

The CREATE TABLE Statement for the The CREATE TABLE Statement for the Audit_Employee TableAudit_Employee Table

CREATE TABLE audit_employee (CREATE TABLE audit_employee (

emp_ssn CHAR(9),emp_ssn CHAR(9),

old_salary MONEY,old_salary MONEY,

new_salary MONEY, new_salary MONEY,

system_user_name CHAR(20),system_user_name CHAR(20),

datetime_changed DATETIME,datetime_changed DATETIME,

CONSTRAINT pk_audit_employee CONSTRAINT pk_audit_employee

PRIMARY KEY (emp_ssn, PRIMARY KEY (emp_ssn, datetime_changed) );datetime_changed) );

Page 27: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 27

Creating/Testing the Update Salary TriggerCreating/Testing the Update Salary Trigger CREATE TRIGGER update_salaryCREATE TRIGGER update_salary ON employee AFTER UPDATEON employee AFTER UPDATE AS IF UPDATE(emp_salary)AS IF UPDATE(emp_salary) BEGINBEGIN DECLARE @emp_ssn CHAR(9)DECLARE @emp_ssn CHAR(9) DECLARE @old_salary MONEYDECLARE @old_salary MONEY DECLARE @new_salary MONEYDECLARE @new_salary MONEY SELECT @old_salary = (SELECT emp_salary SELECT @old_salary = (SELECT emp_salary FROM deleted)FROM deleted) SELECT @new_salary = (SELECT emp_salary SELECT @new_salary = (SELECT emp_salary FROM inserted)FROM inserted) SELECT @emp_ssn = (SELECT emp_ssn SELECT @emp_ssn = (SELECT emp_ssn FROM inserted)FROM inserted) INSERT INTO audit_employee VALUES (@emp_ssn, INSERT INTO audit_employee VALUES (@emp_ssn,

@old_salary, @new_salary, USER_NAME(), GETDATE())@old_salary, @new_salary, USER_NAME(), GETDATE()) END END

Page 28: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 28

Page 29: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 29

Understanding the Update Salary TriggerUnderstanding the Update Salary Trigger• The trigger fires when an UPDATE occurs to a row of the The trigger fires when an UPDATE occurs to a row of the

employeeemployee table as specified by the ON clause. table as specified by the ON clause. • The AS clause object is the IF UPDATE specification for The AS clause object is the IF UPDATE specification for

the the emp_salaryemp_salary column of the column of the employeeemployee table. table. • The BEGIN and END statements denote the trigger code.The BEGIN and END statements denote the trigger code.

– Three variables are declared that store the employee social security Three variables are declared that store the employee social security number, old salary, and new salary (number, old salary, and new salary (@emp_ssn@emp_ssn, , @old_salary@old_salary, , @new_salary@new_salary). ).

– The data types for the variables match the associated columns in The data types for the variables match the associated columns in the the employeeemployee table. table.

– SELECT statements store values to the three variables by selecting SELECT statements store values to the three variables by selecting from two virtual tables in SQL Server named from two virtual tables in SQL Server named deleteddeleted and and inserted inserted (these two tables are described later). (these two tables are described later).

– An INSERT statement inserts a row into the An INSERT statement inserts a row into the audit_employeeaudit_employee table. table.

– The USER_NAME( ) and GETDATE( ) functions extract the The USER_NAME( ) and GETDATE( ) functions extract the system user name and date of the modification from system tables.system user name and date of the modification from system tables.

Page 30: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 30

Testing the Update Salary TriggerTesting the Update Salary Trigger

• Test the trigger by executing the Test the trigger by executing the individual_raiseindividual_raise procedure created earlier. Assign employee Bock with procedure created earlier. Assign employee Bock with social security number 999-11-1111 a 5% raise. social security number 999-11-1111 a 5% raise.

EXEC individual_raise @emp_ssn=999111111, EXEC individual_raise @emp_ssn=999111111, @percent_raise=5.0@percent_raise=5.0

SSN Last Name Old Salary SSN Last Name Old Salary --------- ---------------------- ---------- --------- ---------------------- ---------- 999111111 Bock 33,217.50999111111 Bock 33,217.50(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)SSN Last Name New Salary SSN Last Name New Salary --------- ---------------------- ---------- --------- ---------------------- ---------- 999111111 Bock 34,878.38999111111 Bock 34,878.38

Page 31: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 31

Audit_Employee Table ResultsAudit_Employee Table Results

• The The update_salaryupdate_salary trigger stored one row in the trigger stored one row in the audit_employeeaudit_employee table. table.

• System user named System user named dbodbo made the update at 1:48 a.m. made the update at 1:48 a.m. • The audit trail is invisible to any employee making salary The audit trail is invisible to any employee making salary

modifications.modifications. SELECT emp_ssn "SSN", SELECT emp_ssn "SSN", CONVERT(CHAR(10), old_salary, 1) "Old Salary",CONVERT(CHAR(10), old_salary, 1) "Old Salary", CONVERT(CHAR(10), new_salary, 1) "New Salary", CONVERT(CHAR(10), new_salary, 1) "New Salary", CAST(system_user_name AS CHAR(8)) "Who", CAST(system_user_name AS CHAR(8)) "Who", CAST(datetime_changed AS CHAR(23)) "On DateTime" CAST(datetime_changed AS CHAR(23)) "On DateTime" FROM audit_employee;FROM audit_employee;SSN Old Salary New Salary Who On DateTime SSN Old Salary New Salary Who On DateTime --------- ---------- ---------- -------- --------- ---------- ---------- --------

------------------- ------------------- 999111111 33,217.50 34,878.38 dbo May 9 2003 999111111 33,217.50 34,878.38 dbo May 9 2003

1:48AM1:48AM

Page 32: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 32

Page 33: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 33

The DELETED & INSERTED Virtual TablesThe DELETED & INSERTED Virtual Tables

• These two virtual tables are used in the These two virtual tables are used in the update_salaryupdate_salary trigger. trigger.

• The structure for these two virtual tables is The structure for these two virtual tables is automatically created by SQL Server. Their automatically created by SQL Server. Their column names/data types are identical to the table column names/data types are identical to the table ((employeeemployee in this case) referenced by a trigger. in this case) referenced by a trigger.

• The The deleteddeleted table is used to refer to values before table is used to refer to values before the action that fires the trigger while the the action that fires the trigger while the insertedinserted table is used to refer to values after the action that table is used to refer to values after the action that fires the trigger. fires the trigger.

Page 34: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 34

The DELETED & INSERTED Virtual The DELETED & INSERTED Virtual Tables (Cont.)Tables (Cont.)

• When data rows are inserted or deleted, these two When data rows are inserted or deleted, these two virtual tables store copies of the rows that are virtual tables store copies of the rows that are deleted and inserted. deleted and inserted.

• When rows are updated, the When rows are updated, the deleteddeleted virtual table virtual table stores copies of the rows before an UPDATE stores copies of the rows before an UPDATE statement executes and the statement executes and the insertedinserted virtual table virtual table stores copies of the rows after an UPDATE stores copies of the rows after an UPDATE statement executes.statement executes.

Page 35: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 35

Trigger Example #2 – Enforcing a Business RuleTrigger Example #2 – Enforcing a Business Rule

• Example business rule: No employee may receive a Example business rule: No employee may receive a pay raise that exceeds 10% of their current base salary.pay raise that exceeds 10% of their current base salary.

• The The check_salary_raisecheck_salary_raise trigger checks the % of a raise trigger checks the % of a raise and if the new employee salary figure is 10% larger and if the new employee salary figure is 10% larger than the old salary figure, the UPDATE transaction is than the old salary figure, the UPDATE transaction is canceled through use of a ROLLBACK canceled through use of a ROLLBACK TRANSACTION statement.TRANSACTION statement.

• The old and new salary figures are stored to variables The old and new salary figures are stored to variables from the from the deleteddeleted and and insertedinserted virtual tables, and virtual tables, and compared to evaluate the % of salary raise.compared to evaluate the % of salary raise.

Page 36: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 36

Check_Salary_Raise Trigger CodeCheck_Salary_Raise Trigger CodeCREATE TRIGGER check_salary_raiseCREATE TRIGGER check_salary_raise ON employee AFTER UPDATEON employee AFTER UPDATE AS IF UPDATE(emp_salary)AS IF UPDATE(emp_salary) BEGINBEGIN DECLARE @old_salary MONEYDECLARE @old_salary MONEY DECLARE @new_salary MONEYDECLARE @new_salary MONEY SELECT @old_salary = (SELECT emp_salary FROM deleted)SELECT @old_salary = (SELECT emp_salary FROM deleted) SELECT @new_salary = (SELECT emp_salary FROM inserted)SELECT @new_salary = (SELECT emp_salary FROM inserted) IF @new_salary > @old_salary * 1.1IF @new_salary > @old_salary * 1.1 BEGINBEGIN PRINT 'Salary Raise Exceeds Policy Limits'PRINT 'Salary Raise Exceeds Policy Limits' ROLLBACK TRANSACTIONROLLBACK TRANSACTION ENDEND ELSEELSE BEGINBEGIN PRINT 'Salary Raise Approved'PRINT 'Salary Raise Approved' ENDEND END;END;

Page 37: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 37

A Valid Raise % TestA Valid Raise % Test

• The EXEC of the The EXEC of the individual_raisindividual_raise procedure fires the e procedure fires the check_salary_raisecheck_salary_raise trigger as evidenced by the trigger as evidenced by the Salary Raise Salary Raise ApprovedApproved message. message.

EXEC individual_raise @emp_ssn=999111111, EXEC individual_raise @emp_ssn=999111111, @percent_raise=5.0@percent_raise=5.0 SSN Last Name Old Salary SSN Last Name Old Salary --------- ------------------------- ---------- --------- ------------------------- ---------- 999111111 Bock 34,878.38999111111 Bock 34,878.38

Salary Raise ApprovedSalary Raise Approved

SSN Last Name New Salary SSN Last Name New Salary --------- ------------------------- ---------- --------- ------------------------- ---------- 999111111 Bock 36,622.29999111111 Bock 36,622.29

Page 38: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 38

Audit_Employee Table ResultsAudit_Employee Table Results

• The The audit_employeeaudit_employee table now has two rows – a new one table now has two rows – a new one reflecting the result of the earlier reflecting the result of the earlier update_salaryupdate_salary trigger firing. trigger firing.

SELECT emp_ssn "SSN", SELECT emp_ssn "SSN", CONVERT(CHAR(10), old_salary, 1) "Old Salary",CONVERT(CHAR(10), old_salary, 1) "Old Salary", CONVERT(CHAR(10), new_salary, 1) "New Salary", CONVERT(CHAR(10), new_salary, 1) "New Salary", CAST(system_user_name AS CHAR(8)) "Who", CAST(system_user_name AS CHAR(8)) "Who", CAST(datetime_changed AS CHAR(23)) "On DateTime" CAST(datetime_changed AS CHAR(23)) "On DateTime" FROM audit_employee;FROM audit_employee;SSN Old Salary New Salary Who On DateTime SSN Old Salary New Salary Who On DateTime --------- --------- ---------- ---- ------------------- --------- --------- ---------- ---- ------------------- 999111111 33,217.50 34,878.38 dbo May 9 2003 1:48AM 999111111 33,217.50 34,878.38 dbo May 9 2003 1:48AM

999111111 34,878.38 36,622.29 dbo May 9 2003 4:36PM 999111111 34,878.38 36,622.29 dbo May 9 2003 4:36PM

Page 39: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 39

An Invalid Raise % TestAn Invalid Raise % Test

• An invalid raise of 11% for employee Bordoloi An invalid raise of 11% for employee Bordoloi will cause the will cause the check_salary_raisecheck_salary_raise trigger to trigger to display the display the Salary Raise Exceeds Policy LimitsSalary Raise Exceeds Policy Limits message. message.

• Because the transaction was canceled by the Because the transaction was canceled by the ROLLBACK TRANSACTION statement, the ROLLBACK TRANSACTION statement, the audit_employeeaudit_employee table will not have any record of table will not have any record of

the modification.the modification.

Page 40: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 40

An Invalid Raise % Test (Cont.)An Invalid Raise % Test (Cont.)

EXEC individual_raise @emp_ssn=999666666, EXEC individual_raise @emp_ssn=999666666, @percent_raise=11.0@percent_raise=11.0

SSN Last Name Old Salary SSN Last Name Old Salary --------- --------------------- ---------- --------- --------------------- ---------- 999666666 Bordoloi 60,898.75999666666 Bordoloi 60,898.75(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)Salary Raise Exceeds Policy LimitsSalary Raise Exceeds Policy LimitsMsg 3609, Level 16, State 1, Procedure individual_raise, Line 6Msg 3609, Level 16, State 1, Procedure individual_raise, Line 6

The transaction ended in the trigger. The batch has been aborted.The transaction ended in the trigger. The batch has been aborted.

Page 41: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 41

Defining the Order of Trigger ExecutionDefining the Order of Trigger Execution

• Because SQL Server allows more than one trigger Because SQL Server allows more than one trigger for a table or view, it is sometimes important to for a table or view, it is sometimes important to specify the order in which triggers execute. specify the order in which triggers execute.

• By definition, triggers execute in the order in By definition, triggers execute in the order in which they are created.which they are created.

• Revise our scenario by dropping the two triggers Revise our scenario by dropping the two triggers and recreating the and recreating the update_salaryupdate_salary trigger to include trigger to include a COMMIT statement; then, recreating the a COMMIT statement; then, recreating the check_salary_raisecheck_salary_raise trigger. trigger.

Page 42: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 42

Redefined Update_Salary TriggerRedefined Update_Salary TriggerCREATE TRIGGER update_salaryCREATE TRIGGER update_salary ON employee AFTER UPDATEON employee AFTER UPDATE AS IF UPDATE(emp_salary)AS IF UPDATE(emp_salary) BEGINBEGIN DECLARE @emp_ssn CHAR(9)DECLARE @emp_ssn CHAR(9) DECLARE @old_salary MONEYDECLARE @old_salary MONEY DECLARE @new_salary MONEYDECLARE @new_salary MONEY SELECT @old_salary = (SELECT emp_salary SELECT @old_salary = (SELECT emp_salary FROM deleted)FROM deleted) SELECT @new_salary = (SELECT emp_salary SELECT @new_salary = (SELECT emp_salary FROM inserted)FROM inserted) SELECT @emp_ssn = (SELECT emp_ssn FROM inserted)SELECT @emp_ssn = (SELECT emp_ssn FROM inserted) INSERT INTO audit_employee VALUESINSERT INTO audit_employee VALUES (@emp_ssn, @old_salary, @new_salary, (@emp_ssn, @old_salary, @new_salary, USER_NAME(), GETDATE())USER_NAME(), GETDATE()) COMMITCOMMIT END END

Page 43: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 43

Resetting the Trigger Firing OrderResetting the Trigger Firing Order

• Use the system stored procedure named Use the system stored procedure named sp_settriggerordersp_settriggerorder (read set trigger order) for an individual event such as an (read set trigger order) for an individual event such as an AFTER UPDATE transaction. AFTER UPDATE transaction.

• Use the parameter Use the parameter @order@order to specify values of either: (1) to specify values of either: (1) FIRST, (2) LAST, or (3) NONE – these specify if a trigger FIRST, (2) LAST, or (3) NONE – these specify if a trigger is to fire FIRST or LAST as an AFTER trigger. is to fire FIRST or LAST as an AFTER trigger.

• TheThe @stmttype @stmttype parameter specifies the type of DML parameter specifies the type of DML transaction – (1) update, (2), delete, or (3) insert.transaction – (1) update, (2), delete, or (3) insert.

EXEC sp_settriggerorder EXEC sp_settriggerorder @triggername='check_salary_raise', @triggername='check_salary_raise',

@order='first', @stmttype='update'@order='first', @stmttype='update'

Page 44: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 44

Testing the Trigger Firing OrderTesting the Trigger Firing Order

• Test the trigger firing order by attempting to increase Test the trigger firing order by attempting to increase Bordoloi’s salary by 11% (violates the business rule).Bordoloi’s salary by 11% (violates the business rule).

• The The check_salary_raisecheck_salary_raise trigger fires first and rejects the trigger fires first and rejects the pay raise. The update operation is rolled back.pay raise. The update operation is rolled back.

EXEC individual_raise @emp_ssn=999666666, EXEC individual_raise @emp_ssn=999666666, @percent_raise=11.0@percent_raise=11.0

SSN Last Name Old Salary SSN Last Name Old Salary

--------- -------------------- ---------- --------- -------------------- ----------

999666666 Bordoloi 67,597.61999666666 Bordoloi 67,597.61

(1 row(s) affected)(1 row(s) affected)

Salary Raise Exceeds Policy LimitsSalary Raise Exceeds Policy Limits

Page 45: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 45

Effect of Trigger Firing Order on the Effect of Trigger Firing Order on the Audit_Employee TableAudit_Employee Table

• Since Bordoloi’s raise was rolled back, will a row Since Bordoloi’s raise was rolled back, will a row still be inserted into the still be inserted into the audit_employeeaudit_employee table? table?

• No, because row insertions would first be written No, because row insertions would first be written to the to the insertedinserted virtual table; however, the virtual table; however, the check_salary_raisecheck_salary_raise trigger fired and rolled the trigger fired and rolled the transaction back. transaction back.

• Rolling back the transaction canceled the raise and Rolling back the transaction canceled the raise and the the update_salary update_salary trigger never fires.trigger never fires.

Page 46: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 46

INSTEAD OF TriggersINSTEAD OF Triggers

• An INSTEAD OF trigger fires in place of a triggering event An INSTEAD OF trigger fires in place of a triggering event such as an UPDATE or INSERT transaction. such as an UPDATE or INSERT transaction.

• INSTEAD OF triggers execute after SQL Server creates the INSTEAD OF triggers execute after SQL Server creates the insertedinserted and and deleteddeleted virtual tables, so the data rows for the virtual tables, so the data rows for the triggering event are stored to these two virtual tables, but any triggering event are stored to these two virtual tables, but any existing integrity constraints and triggers checking business existing integrity constraints and triggers checking business rules have not yet fired. rules have not yet fired.

• INSTEAD OF triggers can be created on both views and INSTEAD OF triggers can be created on both views and tables, whereas AFTER triggers can only be created for tablestables, whereas AFTER triggers can only be created for tables—an important advantage of this type of trigger. —an important advantage of this type of trigger.

• INSTEAD OF triggers use the data rows found in the INSTEAD OF triggers use the data rows found in the insertedinserted and and deleteddeleted virtual tables for views that are in use to complete virtual tables for views that are in use to complete any required DML transaction. any required DML transaction.

Page 47: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 47

A Project and Equipment ViewA Project and Equipment View

• The The project_equipmentproject_equipment view displays information view displays information about equipment used on various projects.about equipment used on various projects.

• The column named The column named eqp_total_valueeqp_total_value is a computed is a computed (derived) column in the (derived) column in the equipmentequipment base table. base table.

CREATE VIEW project_equipment ASCREATE VIEW project_equipment AS SELECT pro_number, pro_name, eqp_no, SELECT pro_number, pro_name, eqp_no, eqp_description, eqp_value, eqp_description, eqp_value, eqp_qty_on_hand, eqp_total_valueeqp_qty_on_hand, eqp_total_value FROM project JOIN equipment ONFROM project JOIN equipment ON (eqp_pro_number = pro_number)(eqp_pro_number = pro_number)

Page 48: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 48

An Attempted UpdateAn Attempted Update• Project 30 has one printer allocated (Project 30 has one printer allocated (eqp_numbereqp_number = '5678') = '5678')• Allocating another printer of the same type to project 30 Allocating another printer of the same type to project 30

requires an UPDATE operation that attempts to use the requires an UPDATE operation that attempts to use the project_equipmentproject_equipment view. view.

• This yields an error – the computed column This yields an error – the computed column eqp_total_valueeqp_total_value (referenced as derived in the error (referenced as derived in the error message) cannot be specified for update through use of a message) cannot be specified for update through use of a view. This is a limitation of views.view. This is a limitation of views.

UPDATE project_equipment SET eqp_qty_on_hand = 2,UPDATE project_equipment SET eqp_qty_on_hand = 2, eqp_value = 172.00, eqp_total_value = 344.00eqp_value = 172.00, eqp_total_value = 344.00 WHERE pro_number = 30 AND eqp_no='5678';WHERE pro_number = 30 AND eqp_no='5678';

Server: Msg 4406, Level 16, State 2, Line 1Server: Msg 4406, Level 16, State 2, Line 1Update or insert of view or function Update or insert of view or function

'project_equipment' failed because it contains 'project_equipment' failed because it contains a derived or constant field.a derived or constant field.

Page 49: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 49

Creating an INSTEAD OF TriggerCreating an INSTEAD OF Trigger• The Trigger fires for the The Trigger fires for the project_equipmentproject_equipment view, but updates the view, but updates the

equipmentequipment table directly from values in the table directly from values in the insertedinserted virtual table. virtual table.

CREATE TRIGGER update_eqp_total_value ON CREATE TRIGGER update_eqp_total_value ON project_equipmentproject_equipment

INSTEAD OF UPDATEINSTEAD OF UPDATE AS BEGINAS BEGIN DECLARE @pro_number SMALLINTDECLARE @pro_number SMALLINT DECLARE @eqp_no CHAR(4)DECLARE @eqp_no CHAR(4) SELECT @pro_number = (SELECT pro_number SELECT @pro_number = (SELECT pro_number FROM inserted)FROM inserted) SELECT @eqp_no = (SELECT eqp_no FROM inserted) SELECT @eqp_no = (SELECT eqp_no FROM inserted) UPDATE equipment SET eqp_qty_on_hand = 2 UPDATE equipment SET eqp_qty_on_hand = 2 WHERE eqp_pro_number = @pro_number ANDWHERE eqp_pro_number = @pro_number AND eqp_no=@eqp_noeqp_no=@eqp_no END;END;

Page 50: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 50

Executing an UPDATE TransactionExecuting an UPDATE Transaction

• When the UPDATE transaction shown earlier was executed, the When the UPDATE transaction shown earlier was executed, the equipmentequipment base table was not updated – the UPDATE failed. base table was not updated – the UPDATE failed.

• Now a re-execution of the UPDATE actually causes the UPDATE Now a re-execution of the UPDATE actually causes the UPDATE statement specified as part of the INSTEAD OF trigger executes. statement specified as part of the INSTEAD OF trigger executes.

• Now the update executes and the new information for the equipment Now the update executes and the new information for the equipment and project is shown by the SELECT statement.and project is shown by the SELECT statement.

• The value stored in the The value stored in the eqp_total_valueeqp_total_value column was automatically column was automatically updated to $344.00 because this column is derived.updated to $344.00 because this column is derived.

SELECT pro_number, eqp_no, eqp_value, eqp_qty_on_hand, SELECT pro_number, eqp_no, eqp_value, eqp_qty_on_hand, eqp_total_value eqp_total_value FROM project_equipmentFROM project_equipment WHERE pro_number = 30 and eqp_no='5678';WHERE pro_number = 30 and eqp_no='5678'; pro_number eqp_no eqp_value eqp_qty_on_hand eqp_total_value pro_number eqp_no eqp_value eqp_qty_on_hand eqp_total_value

---------- ------ --------- --------------- ------------------------- ------ --------- --------------- --------------- 30 5678 172.0000 2 344.000030 5678 172.0000 2 344.0000

Page 51: Prentice Hall © 20041 COS 346 Day 16. 7-2 Agenda Questions?Questions? Assignment 6 CorrectedAssignment 6 Corrected –7 A’s and 1 late assignment Assignment

Prentice Hall © 2004 51

SummarySummary• Stored procedures are small programs that exist as Stored procedures are small programs that exist as

database objects. database objects. – They can automate batch process for tasks such as audit trail They can automate batch process for tasks such as audit trail

creation. creation. – Stored procedures execute efficiently as they are compiled Stored procedures execute efficiently as they are compiled

and stored as database objects.and stored as database objects.• Triggers are database objects that fire based on Triggers are database objects that fire based on

specified DML events.specified DML events.– Triggers enforce business rules.Triggers enforce business rules.– AFTER triggers can enforce integrity constraints for tables AFTER triggers can enforce integrity constraints for tables

while INSTEAD OF triggers can enforce integrity constraints while INSTEAD OF triggers can enforce integrity constraints for both views and tables. for both views and tables.

– The order of trigger execution when a table has multiple The order of trigger execution when a table has multiple triggers is specified with the triggers is specified with the sp_settriggerordersp_settriggerorder system system procedure. procedure.