如何在Azure中自动增加现有主键?
答案 0 :(得分:4)
您的表必须从头开始重建,无法将auto_increment分配给现有表。试试这个脚本,它将使用auto_increment为你构建一个表,将旧表中的所有数据传输到新表,删除旧表并将新表重命名为旧表。
确保您的数据与auto_increment属性兼容!
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_schema_version
(
version int NULL,
datetime datetime NULL,
comments nvarchar(150) NULL,
id int NOT NULL IDENTITY (1, 1)
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_schema_version SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_schema_version ON
GO
IF EXISTS(SELECT * FROM dbo.schema_version)
EXEC('INSERT INTO dbo.Tmp_schema_version (version, datetime, comments, id)
SELECT version, datetime, comments, id FROM dbo.schema_version WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_schema_version OFF
GO
DROP TABLE dbo.schema_version
GO
EXECUTE sp_rename N'dbo.Tmp_schema_version', N'schema_version', 'OBJECT'
GO
ALTER TABLE dbo.schema_version ADD CONSTRAINT
PK_schema_version PRIMARY KEY CLUSTERED
(
id
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
答案 1 :(得分:0)
这几乎与@Dieter Gobeyn的解决方案类似;我后来跟着他。
使用
上的自动增量创建临时表CREATE TABLE [dbo].[schema_version_new](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Version] [int] NULL,
[DateTime] [datetime] NULL,
[Comments] [nvarchar](150) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)
) ON [PRIMARY]
GO
将旧表中的所有内容复制到新创建的表中;我们故意将ID留在旧表后面,我们在新表上放置了自动增量ID,所以不需要在那里放ID。如果我们需要保留旧表的ID,那么我们需要“SET IDENTITY_INSERT dbo.schema_version_new OFF
”,在插入行时包含ID,插入后我们再次打开identity_insert“SET IDENTITY_INSERT dbo.schema_version_new ON
”。对于新插入,它将获得自动ID。
INSERT INTO [schema_version_new]([Version], [Datetime], [Comments])
SELECT [Version], [Datetime], [Comments] FROM [schema_version]
放下旧桌子。
DROP TABLE [dbo].[schema_version]
GO
将新表重命名为旧表的名称。
EXECUTE sp_rename N'dbo.schema_version_new', N'schema_version', 'OBJECT'
GO