SELECT
(CASE WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED' ELSE 'DISABLED' END) AS STATUS
,OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME
,OBJECT_NAME(FKEYID) AS TABLE_NAME
,COL_NAME(FKEYID, FKEY) AS COLUMN_NAME
,OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME
,COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
FROM SYSFOREIGNKEYS
ORDER BY TABLE_NAME
, CONSTRAINT_NAME
, REFERENCED_TABLE_NAME
, KEYNO
http://www.jasinskionline.com/TechnicalWiki/Disable-Every-Foreign-Key.ashx?AspxAutoDetectCookieSupport=1
For SQL 2005 and above:
-- This SQL generates a set of SQL statements to disable every foreign
-- key in the database
select distinct
sql = 'ALTER TABLE [' + onSchema.name + '].[' + onTable.name +
'] NOCHECK CONSTRAINT [' + foreignKey.name + ']'
from sysforeignkeys fk inner join sysobjects foreignKey
on foreignKey.id = fk.constid
inner join sys.objects onTable
on fk.fkeyid = onTable.object_id
inner join sys.schemas onSchema
on onSchema.schema_id = onTable.schema_id
inner join sysobjects againstTable
on fk.rkeyid = againstTable.id
where againstTable.TYPE = 'U'
and onTable.TYPE = 'U'
and ObjectProperty(fk.constid,'CnstIsDisabled') = 0
order by 1
-- This SQL generates a set of SQL statements to re-enable every foreign
-- key in the database
select distinct
sql = 'ALTER TABLE [' + onSchema.name + '].[' + onTable.name +
'] CHECK CONSTRAINT [' + foreignKey.name + ']'
from sysforeignkeys fk inner join sysobjects foreignKey
on foreignKey.id = fk.constid
inner join sys.objects onTable
on fk.fkeyid = onTable.object_id
inner join sys.schemas onSchema
on onSchema.schema_id = onTable.schema_id
inner join sysobjects againstTable
on fk.rkeyid = againstTable.id
where againstTable.TYPE = 'U'
and onTable.TYPE = 'U'
and ObjectProperty(fk.constid,'CnstIsDisabled') = 1
order by 1
No comments:
Post a Comment