SQL SERVER 给一个大表添加自增主建 执行过程解析

/* 为了防止任何可能出现的数据丢失问题,您应该先仔细检查此脚本,然后再在数据库设计器的上下文之外运行此脚本。*/

-- 设置参数
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_EmailUser
 (
 ID bigint NOT NULL IDENTITY (1, 1),
 CreateTime datetime NULL,
 ReceTime datetime NULL,
 ServerID int NULL,
 Email varchar(250) NULL,
 Status int NULL,
 IsDel int NULL,
 MailNum bigint NULL,
 Msg ntext NULL
 )  ON [PRIMARY]
  TEXTIMAGE_ON [PRIMARY]
GO

 

--设置自增加长状态
SET IDENTITY_INSERT dbo.Tmp_EmailUser ON

 

-- 开始拷贝表数据到临时表
GO
IF EXISTS(SELECT * FROM dbo.EmailUser)
  EXEC('INSERT INTO dbo.Tmp_EmailUser (ID, CreateTime, ReceTime, ServerID, Email, Status, IsDel, MailNum, Msg)
  SELECT ID, CreateTime, ReceTime, ServerID, Email, Status, IsDel, MailNum, Msg FROM dbo.EmailUser WITH (HOLDLOCK TABLOCKX)')

 

-- 设置自增长列状态
GO
SET IDENTITY_INSERT dbo.Tmp_EmailUser OFF

 

-- 删除原来表
GO
DROP TABLE dbo.EmailUser

 

-- 对临时表进行改名
GO
EXECUTE sp_rename N'dbo.Tmp_EmailUser', N'EmailUser', 'OBJECT'

 

-- 添加主键
GO
ALTER TABLE dbo.EmailUser ADD CONSTRAINT
 PK_EmailUser PRIMARY KEY CLUSTERED
 (
 ID
 ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO

 

-- 添加索引
CREATE NONCLUSTERED INDEX IX_EmailUser ON dbo.EmailUser
 (
 Email
 ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值