house9

random code and what not

MSSQL drop and re-add constraints

One of the guys at work hooked me up with this code - quite useful if you want to do a bunch of data inserts but don’t want to worry about the order you apply the inserts because of foreign key constraints

Before performing data actions:
-- generate these and run
SELECT
'ALTER TABLE ' + so.NAME + ' NOCHECK CONSTRAINT ALL'
FROM sysobjects so
WHERE xtype = 'u'

After performing data actions:
-- generate these and run
SELECT
'ALTER TABLE ' + so.NAME + ' CHECK CONSTRAINT ALL'
FROM sysobjects so
WHERE xtype = 'u'

Thanks to ET for this code bit!