Dumies collection

Page 305

Chapter 14: Protecting Data After the first preceding UPDATE statement, the implementation checks all constraints that reference values that the statement modifies. This includes the constraint defined in the DEPT table, because that constraint references the Salary column of the EMPLOYEE table and the UPDATE statement is modifying that column. After the first UPDATE statement, that constraint is violated. You assume that before you execute the UPDATE statement the database is correct, and each Payroll value in the DEPT table equals the sum of the Salary values in the corresponding columns of the EMPLOYEE table. When the first UPDATE statement increases a Salary value, this equality is no longer true. The second UPDATE statement corrects this and again leaves the database values in a state for which the constraint is True. Between the two updates, the constraint is False. The SET CONSTRAINTS DEFERRED statement lets you temporarily disable or suspend all constraints, or only specified constraints. The constraints are deferred until either you execute a SET CONSTRAINTS IMMEDIATE statement, or you execute a COMMIT or ROLLBACK statement. So you surround the previous two UPDATE statements with SET CONSTRAINTS statements. The code looks like this: SET CONSTRAINTS DEFERRED ; UPDATE EMPLOYEE SET Salary = Salary + 100 WHERE EmpNo = ‘123’ ; UPDATE DEPT D SET Payroll = Payroll + 100 WHERE D.DeptNo = (SELECT E.DeptNo FROM EMPLOYEE E WHERE E.EmpNo = ‘123’) ; SET CONSTRAINTS IMMEDIATE ; This procedure defers all constraints. If you insert new rows into DEPT, the primary keys won’t be checked; you have removed protection that you may want to keep. Instead, you should specify the constraints that you want to defer. To do this, name the constraints when you create them: CREATE TABLE DEPT (DeptNo CHAR(5), DeptName CHAR(20), Payroll DECIMAL(15,2), CONSTRAINT PayEqSumsal CHECK (Payroll = SELECT SUM(Salary) FROM EMPLOYEE E WHERE E.DeptNo = DEPT.DeptNo)) ;

285


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.