INF: Deferred Constraints and Disable_Def_Cnst_ChkID: Q150874
|
SQL Server version 6.5 has the ability to disable deferred constraint checking. Deferred constraints are described in this article; examples showing the effects of disabling them with the use of SET Disable_Def_Cnst_Chk ON are also provided.
By default, constraints are checked during the execution of a statement
for each row that the statement affects and then perhaps again after all
rows have been modified. This is necessary because an UPDATE statement
might make a change to a row that by itself might seem to violate a
constraint, but when viewed with all of the subsequent changes to other
rows (by the same statement execution), the table is left in a
consistent state. As constraints are checked for each row, any apparent
violations are marked for rechecking and "deferred." Once all rows have
been updated, all marked rows have their constraints rechecked (this is
"deferred constraint checking"); if any violations now occur, the
execution of the statement fails; and if no violation occurs, the statement
succeeds.
For example: The def_employee table has a primary key on emp_id and a
self-referencing foreign key from the mgr_id to emp_id. The statements
to create this table and populate it with 5 rows are given below. The
inserts are followed by updates so the employees will not have to be
inserted in order with the managers entered first.
DROP TABLE def_employee
go
CREATE TABLE def_employee (
emp_id INT NOT NULL PRIMARY KEY,
name CHAR(10),
mgr_id INT NULL REFERENCES def_employee)
go
INSERT def_employee VALUES ( 1, 'VP', NULL)
INSERT def_employee VALUES ( 2, 'PRES', NULL)
INSERT def_employee VALUES ( 4, 'JOE', NULL)
INSERT def_employee VALUES ( 6, 'CEO', NULL)
INSERT def_employee VALUES ( 8, 'MGR', NULL)
UPDATE def_employee SET mgr_id = 2 WHERE emp_id = 1
UPDATE def_employee SET mgr_id = 6 WHERE emp_id = 2
UPDATE def_employee SET mgr_id = 8 WHERE emp_id = 4
UPDATE def_employee SET mgr_id = 6 WHERE emp_id = 6
UPDATE def_employee SET mgr_id = 1 WHERE emp_id = 8
SELECT * FROM def_employee
emp_id name mgr_id
----------- ---------- -----------
1 VP 2
2 PRES 6
4 JOE 8
6 CEO 6
8 MGR 1
UPDATE def_employee
SET emp_id = emp_id + 1000,
mgr_id = mgr_id + 1000
SELECT * FROM def_employee
emp_id name mgr_id
----------- ---------- -----------
1001 VP 1002
1002 PRES 1006
1004 JOE 1008
1006 CEO 1006
1008 MGR 1001
SET DISABLE_DEF_CNST_CHK ON
GO
UPDATE def_employee
SET emp_id = emp_id - 1000,
mgr_id = mgr_id - 1000
Msg 547, Level 16, State 2
UPDATE statement conflicted with COLUMN REFERENCE constraint
'FK__def_emplo__mgr_i__496EF0FC'. The conflict occurred in database
'pubs', table 'def_employee', column 'mgr_id'
Command has been aborted.
Keywords : kbusage SSrvInst SSrvProg
Version : 6.5
Platform : WINDOWS
Issue type : kbhowto
Last Reviewed: March 25, 1999