alter table tb drop column id go alter table tb add id int identity go
--参考:--创建测试表 CREATE TABLE t1(ID int IDENTITY,A int) GO --插入记录 INSERT t1 VALUES(1) GO--1. 将IDENTITY(标识)列变为普通列 ALTER TABLE t1 ADD ID_temp int GOUPDATE t1 SET ID_temp=ID ALTER TABLE t1 DROP COLUMN ID EXEC sp_rename N't1.ID_temp',N'ID',N'COLUMN' INSERT t1 VALUES(100,9) GO--2. 将普通列变为标识列 CREATE TABLE t1_temp(ID int,A int IDENTITY) SET IDENTITY_INSERT t1_temp ON INSERT t1_temp(ID,A) SELECT * FROM t1 SET IDENTITY_INSERT t1_temp OFF DROP TABLE T1 GOEXEC sp_rename N't1_temp',N't1' INSERT t1 VALUES(109999) GO--显示处理结果 SELECT * FROM t1 /*--结果: ID A ----------------- ----------- 1 1 100 9 109999 10 --*/
if object_id('tb') is not null drop table tb go create table tb(id int identity(1,1),col varchar(10)) go insert tb(col) select '192' union all select '168' union all select '0' union all select '1' select * from tb /* id col 1 192 2 168 3 0 4 1 */--设置ID从1开始,前提是ID非索引健 dbcc checkident(tb,reseed,0) /* 检查标识信息: 当前标识值 '4',当前列值 '0'。 DBCC 执行完毕。如果 DBCC 输出了错误信息,请与系统管理员联系。*/ insert tb(col) select '192' union all select '168' union all select '0' union all select '1' select * from tb /* id col 1 192 2 168 3 0 4 1 1 192 2 168 3 0 4 1 */
drop column id
go
alter table tb
add id int identity
go
CREATE TABLE t1(ID int IDENTITY,A int)
GO
--插入记录
INSERT t1 VALUES(1)
GO--1. 将IDENTITY(标识)列变为普通列
ALTER TABLE t1 ADD ID_temp int
GOUPDATE t1 SET ID_temp=ID
ALTER TABLE t1 DROP COLUMN ID
EXEC sp_rename N't1.ID_temp',N'ID',N'COLUMN'
INSERT t1 VALUES(100,9)
GO--2. 将普通列变为标识列
CREATE TABLE t1_temp(ID int,A int IDENTITY)
SET IDENTITY_INSERT t1_temp ON
INSERT t1_temp(ID,A) SELECT * FROM t1
SET IDENTITY_INSERT t1_temp OFF
DROP TABLE T1
GOEXEC sp_rename N't1_temp',N't1'
INSERT t1 VALUES(109999)
GO--显示处理结果
SELECT * FROM t1
/*--结果:
ID A
----------------- -----------
1 1
100 9
109999 10
--*/
go
create table tb(id int identity(1,1),col varchar(10))
go
insert tb(col)
select '192'
union all select '168'
union all select '0'
union all select '1'
select * from tb
/*
id col
1 192
2 168
3 0
4 1
*/--设置ID从1开始,前提是ID非索引健
dbcc checkident(tb,reseed,0)
/*
检查标识信息: 当前标识值 '4',当前列值 '0'。
DBCC 执行完毕。如果 DBCC 输出了错误信息,请与系统管理员联系。*/
insert tb(col)
select '192'
union all select '168'
union all select '0'
union all select '1'
select * from tb
/*
id col
1 192
2 168
3 0
4 1
1 192
2 168
3 0
4 1
*/
dbcc checkident(tb,reseed,0)