是否有必要在向表中添加空列之前删除外键,然后重新添加它们?

Che*_*Ze5 2 sql-server-2008 foreign-key

我使用 SqlCompare 生成了一些 SQL Server(2008) 升级脚本。主要目标是添加一个空列。但是,生成的脚本想要在添加列之前删除其他几个表中的外键和目标表的主键。然后它重新添加它们。这是必要的吗?这样做的原因是什么?

Tho*_*ger 6

不,没有必要。请参阅下面的此工作示例:

use TestDatabase;
go

-- create the parent table (houses the PK)
create table dbo.ParentTable
(
    ParentId int identity(1, 1) not null
        constraint PK_ParentTable_ParentId primary key clustered,
    some_int int not null
);
go

-- insert some dummy data
insert into dbo.ParentTable(some_int)
values (5), (4), (3);
go

-- create the child table (houses the FK)
create table dbo.ChildTable
(
    ChildId int identity(1, 1) not null,
    ParentId int not null
        constraint FK_ChildTable_ParentId foreign key references dbo.ParentTable(ParentId)
);
go

-- insert some dummy data
insert into dbo.ChildTable(ParentId)
values (1), (3);
go

-- view the contents of each table
select *
from dbo.ParentTable;
select *
from dbo.ChildTable;

-- add a nullable int column
alter table dbo.ParentTable
add another_col int null;
go

-- view the new layout
select *
from dbo.ParentTable;
select *
from dbo.ChildTable;
Run Code Online (Sandbox Code Playgroud)

正如您在代码中看到的那样,我dbo.ParentTable通过添加一列进行了修改。这是一个成功的操作,主键约束仍然存在。

至于为什么您的第三方软件会这样做,我们可以猜测一整天。但很可能他们这样做是为了处理一些极端情况,而没有先测试当前的操作是否属于这种情况。