How can foreign key constraints be temporarily disabled using T-SQL?

后端 未结 16 2170
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re-create

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 05:40

    Answer marked '905' looks good but does not work.

    Following worked for me. Any Primary Key, Unique Key, or Default constraints CAN NOT be disabled. In fact, if 'sp_helpconstraint '' shows 'n/a' in status_enabled - Means it can NOT be enabled/disabled.

    -- To generate script to DISABLE

    select 'ALTER TABLE ' + object_name(id) + ' NOCHECK CONSTRAINT [' + object_name(constid) + ']'
    from sys.sysconstraints 
    where status & 0x4813 = 0x813 order by object_name(id)
    

    -- To generate script to ENABLE

    select 'ALTER TABLE ' + object_name(id) + ' CHECK CONSTRAINT [' + object_name(constid) + ']'
    from sys.sysconstraints 
    where status & 0x4813 = 0x813 order by object_name(id)
    

提交回复
热议问题