有没有办法为数据库 Azure SQL 禁用和重新启用 FOREIGN KEY 约束

Is there a way to disable and re enable FOREIGN KEY constraints for a database Azure SQL

我正在尝试截断数据库中的一些表。其中一些表有外键。因此,当我尝试截断它们时,出现以下错误。

Cannot truncate table 'IDN_OAUTH2_ACCESS_TOKEN' because it is being referenced by a FOREIGN KEY constraint.

有没有办法在 Azure SQL(Microsoft SQL Azure (RTM) - 12.0.2000.8)中禁用外键约束并重新启用它们?在 MySQL 中,我使用以下脚本完成了相同的操作。

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE TABLE IDN_OAUTH2_ACCESS_TOKEN;

SET FOREIGN_KEY_CHECKS=1;

我认为我们可以编写一些 T-SQL 脚本来实现这一点。用T-SQL拼接T-SQL(增减FK索引)指令

  1. 我们可以使用下面的脚本查询所有的FK,然后将查询结果复制到一个文本中。我们可以使用查询结果重建外键索引。
select
   concat(concat('alter table ',c.CONSTRAINT_SCHEMA),concat('.',fk.TABLE_NAME)),
   concat(' add constraint  ', c.CONSTRAINT_NAME),  --cu.COLUMN_NAME
   concat(' foreign key( ',cu.COLUMN_NAME),
   concat(concat(') references ',c.CONSTRAINT_SCHEMA),concat('.',pk.TABLE_NAME)),
   concat(concat('(',pt.COLUMN_NAME),');')
from
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
    on c.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
    on c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu
    on c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
inner join  (
            select
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            from
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                on i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            where
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    on pt.TABLE_NAME = pk.TABLE_NAME
  1. 我们可以将add constraint替换为drop constraint。如下:

select
   concat(concat('alter table ',c.CONSTRAINT_SCHEMA),concat('.',fk.TABLE_NAME)),
   concat(' drop constraint  ', c.CONSTRAINT_NAME),  --cu.COLUMN_NAME
   concat(' foreign key( ',cu.COLUMN_NAME)
from
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
    on c.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
    on c.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu
    on c.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
inner join  (
            select
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            from
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                on i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            where
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    on pt.TABLE_NAME = pk.TABLE_NAME

因此您可以删除 FK,然后截断一些表,然后重新构建 FK。