Environment: SQL Server 2008
Necessary info:
-- Disable all table constraints
ALTER TABLE MyTable NOCHECK CONSTRAINT ALL
-- Enable all table constraints
ALTER TABLE MyTable CHECK CONSTRAINT ALL
-- Disable single constraint
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint
-- Enable single constraint
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
Background: I need to update id column value of a table which has corresponding data in a child table and integrity enforced by foreign key constraint. Relationship between tables and data excerpt present below. Need to change 'ROLE_EXEMPTION' with value 'ROLE_AMLM_QA1_EXEMPTION'.
Table relationship:
Data in tables:
Script to fulfill the need:
DECLARE @changedValue VARCHAR(100) = 'ROLE_AMLM_QA1_EXCEMPTION',
@originalValue VARCHAR(100) = 'ROLE_EXEMPTION'
;
-- Disable all table constraints
ALTER TABLE wk_sec_role_resource_mapping NOCHECK CONSTRAINT ALL;
-- Update parent table record
UPDATE wk_sec_roles SET role_id=@changedValue WHERE role_id=@originalValue;
-- Update child table record
UPDATE wk_sec_role_resource_mapping SET role_FK=@changedValue WHERE role_FK=@originalValue;
-- Enable all table constraints
ALTER TABLE wk_sec_role_resource_mapping CHECK CONSTRAINT ALL;
DECLARE @changedValue VARCHAR(100) = 'ROLE_AMLM_QA1_EXCEMPTION',
@originalValue VARCHAR(100) = 'ROLE_EXEMPTION'
;
-- Disable all table constraints
ALTER TABLE wk_sec_role_resource_mapping NOCHECK CONSTRAINT ALL;
-- Update parent table record
UPDATE wk_sec_roles SET role_id=@changedValue WHERE role_id=@originalValue;
-- Update child table record
UPDATE wk_sec_role_resource_mapping SET role_FK=@changedValue WHERE role_FK=@originalValue;
-- Enable all table constraints
ALTER TABLE wk_sec_role_resource_mapping CHECK CONSTRAINT ALL;
Necessary info:
-- Disable all table constraints
ALTER TABLE MyTable NOCHECK CONSTRAINT ALL
-- Enable all table constraints
ALTER TABLE MyTable CHECK CONSTRAINT ALL
-- Disable single constraint
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint
-- Enable single constraint
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
No comments:
Post a Comment