id int类型的 ,我想在id原有的数据上实现自增,比如:最后的数字是3682,接着后面是3683 3684,前面的
数据不动
3663
3667
3668
3723
3669
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
数据不动
3663
3667
3668
3723
3669
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
无法对一个已经插入数据的表,更改其int列为自增,只能试试新建一个同结构表,设置ID列为自增,再在set identity_insert on 状态下把已有数据导入到该表.
alter table "2市场部回款开票记录表2"
alter column id int identity(1,1) not null
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
--*/
用sql语句必须先drop该字段,再新add一个自增字段
不能直接alter属性为自增
切记:要改自增只能可视化操作!
go
--> -->
if not object_id(N'T1') is null
drop table T1
Go
Create table T1([ID] int)
Insert T1
select '3663' union all
select '3667' union all
select '3668' union all
--select '3723' union all
select '3669' union all
select '3671' union all
select '3672' union all
select '3673' union all
select '3674' union all
select '3675' union all
select '3676' union all
select '3677' union all
select '3678' union all
select '3679' union all
select '3680' union all
select '3681' union all
select '3682'
Go
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_T1
(
ID int NOT NULL IDENTITY (3682, 1)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_T1 ON
GO
IF EXISTS(SELECT * FROM dbo.T1)
EXEC('INSERT INTO dbo.Tmp_T1 (ID)
SELECT ID FROM dbo.T1 WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_T1 OFF
GO
DROP TABLE dbo.T1
GO
EXECUTE sp_rename N'dbo.Tmp_T1', N'T1', 'OBJECT'
GO
COMMIT
goINSERT T1 DEFAULT VALUES --測試新增
go
Select * from T1 ORDER BY ID