部署错误,"数据库中已存在名为'PK _***'的对象.无法创建约束."

Gre*_*lis 1 sql deployment visual-studio-2012

当我尝试运行我的应用程序时,出现以下错误:

There is already an object named 'PK_***' in the database. Could not create constraint."
Run Code Online (Sandbox Code Playgroud)

这实际上是为了简洁而结合的两个错误.注意: 星号是我自己的; 这不是密钥的实际名称.

我已经在这里搜索了每个帖子,但我似乎无法进一步寻找解决方案.最糟糕的部分?团队中没有其他人在跑步时遇到这些错误,他们也无法确定我的原因.我们都在使用相同的环境,VS 2012 Premium RC.我当然有来自TFS的最新消息.

我想知道是否有其他人遇到类似这样的问题,只有一个人的环境中出现问题/错误?我可以继续运行该应用程序.它似乎按预期运行,但我是唯一一个得到这些错误的人.

Nic*_*rey 6

在SQL Server中,主键或外键等约束本身就是对象,即使它们依赖于"包含"表.

这意味着它们的名称在拥有模式中必须是唯一的.所以,就像执行DDL一样

create table some_schema.foo
(
  id int not null
)
go

create table some_schema.foo
(
  id int not null
)
go
Run Code Online (Sandbox Code Playgroud)

当第二次create table[尝试]执行时会引发错误,执行这样的ddl同样会引发错误:

create table some_schema.foo
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint PK   primary key clustered ( id          ) ,
  constraint AK01 unique nonclustered   ( description ) ,

)
go

create table some_schema.bar
(
  id          int          not null ,
  description varchar(200) not null , 

  constraint PK   primary key clustered ( id          ) ,
  constraint AK01 unique nonclustered   ( description ) ,

)
go
Run Code Online (Sandbox Code Playgroud)

同样会引发错误,因为您尝试创建的约束具有重复的名称.您需要使用表名限定它们,因此:

create table some_schema.foo
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint foo_PK   primary key clustered ( id          ) ,
  constraint foo_AK01 unique nonclustered   ( description ) ,

)
go

create table some_schema.bar
(
  id          int          not null ,
  description varchar(200) not null , 

  constraint bar_PK   primary key clustered ( id          ) ,
  constraint bar_AK01 unique nonclustered   ( description ) ,

)
go
Run Code Online (Sandbox Code Playgroud)

而你的问题就会消失.

在我看来,在欠对象的上下文之外不存在的依赖对象应该在拥有对象的范围内命名,但这不是SQL标准的工作方式.

祝好运!