primary-key – 如何更改SQL Azure上的现有主键?
我想修改SQL Azure表上的现有主键.
它目前有一列,我想添加另一列. 现在,在SQL Server 2008上,这只是一块蛋糕,只是在SSMS,poof中做到了.完成. ALTER TABLE [dbo].[Friend] ADD CONSTRAINT [PK_Friend] PRIMARY KEY CLUSTERED ( [UserId] ASC,[Id] ASC ) 但是,在SQL Azure上,当我尝试执行上述操作时,它当然会失败: 表’朋友’已经在其上定义了主键. 很好,所以我试着放下钥匙: 此版本的SQL Server不支持没有聚簇索引的表.请创建聚簇索引,然后重试. 好的,所以我尝试创建一个临时聚集索引以删除PK: CREATE CLUSTERED INDEX IX_Test ON [Friend] ([UserId],[Id]) 结果如下: 很棒,一个抓住时刻. 如何将UserId列添加到现有PK? 解决方法注意:从Azure SQL数据库v12开始,这些限制不再适用.这不是“主要指数”.存在诸如“主键”之类的东西,并且还存在诸如“聚集索引”之类的东西.不同的概念,经常混淆.考虑到这一区别,让我们重温一下这个问题: Q1)是否可以修改SQL Azure表中的聚簇索引? create table Friend ( UserId int not null,Id int not null); go create clustered index cdxFriend on Friend (UserId,Id); go create clustered index cdxFriend on Friend (Id,UserId) with (drop_existing=on); go Q2)是否可以修改具有主键约束的表的聚簇索引? create table Friend ( UserId int not null,Id int not null identity(1,1),constraint pk_Friend primary key nonclustered (Id)); create clustered index cdxFriend on Friend (UserId,UserId) with (drop_existing=on); go Q3)可以修改表的主键约束吗? create table Friend ( UserId int not null,constraint pk_Friend primary key nonclustered (Id)); go create clustered index cdxFriend on Friend (UserId,Id); go alter table Friend drop constraint pk_Friend; alter table Friend add constraint pk_Friend primary key nonclustered (UserId) go Q4)通过聚簇索引强制执行时,是否可以修改表的主键? create table Friend ( UserId int not null,constraint pk_Friend primary key clustered (UserId,Id)); go alter table Friend drop constraint pk_Friend; alter table Friend add constraint pk_Friend primary key clustered (Id,UserId) go Q5)如果填充表,是否可以通过聚簇索引强制修改表的主键? create table Friend ( UserId int not null,Id)); go insert into Friend (UserId) values (1); delete from Friend; go alter table Friend drop constraint pk_Friend; 作为旁注:如果表被截断,则可以修改约束. 更改填充表的PK约束的解决方法是执行旧的 create table Friend ( UserId int not null,Id)); go insert into Friend (UserId) values (1); go create table FriendNew ( UserId int not null,constraint pk_Friend_New primary key clustered (Id,UserId)); go set identity_insert FriendNew on; insert into FriendNew (UserId,Id) select UserId,Id from Friend; set identity_insert FriendNew off; go begin transaction exec sp_rename 'Friend','FriendOld'; exec sp_rename 'FriendNew','Friend'; commit; go sp_help 'Friend'; sp_rename方法存在一些问题,最重要的是在重命名期间表的权限不会延续,以及外键约束. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |