SQL更改表字段为自增标识
时间:2022-03-15 08:05
--删除主键约束
DECLARE @Constraint_Name varchar (200)
select @Constraint_Name = Name from dbo.sysobjects
where Xtype = ‘PK‘ and Parent_Obj =
(select [ID] from dbo.sysobjects
where id = object_id(N‘[表名称]‘)
and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1)
if @Constraint_Name <> ‘‘
begin
alter table 表名称 drop constraint @Constraint_Name
end
--删除主键字段
-- 何问起 hovertree.com
declare @count int
select @count = count(*) from sysobjects a,syscolumns b
where a.id = b.id and b.name = ‘主键字段名‘ and a.Name = ‘表名称‘
if @count > 0
begin
alter table 表名称 drop column 主键字段名
end
--创建字段,主键,并自增
alter table 表名称 add 主键字段名 int identity(1,1) PRIMARY KEY