SQL Server:如何在包含行的表上设置自动增量:
如果您要复制的表非常大,此策略会将行物理复制大约两次,这可能需要更长的时间。
您可以保存数据,使用自动增量和主键删除并重建表,然后重新加载数据。
我会用一个例子来指导你:
第一步,创建表foobar(无主键或自增):
CREATE TABLE foobar(
id int NOT NULL,
name nchar(100) NOT NULL,
)
第 2 步,插入一些行
insert into foobar values(1, 'one');
insert into foobar values(2, 'two');
insert into foobar values(3, 'three');
第 3 步,将 foobar 数据复制到临时表中:
select * into temp_foobar from foobar
第 4 步,删除表 foobar:
drop table foobar;
第 5 步,使用主键和自增属性重新创建表:
CREATE TABLE foobar(
id int primary key IDENTITY(1, 1) NOT NULL,
name nchar(100) NOT NULL,
)
第 6 步,将临时表中的数据插入 foobar
SET IDENTITY_INSERT temp_foobar ON
INSERT into foobar (id, name) select id, name from temp_foobar;
第 7 步,删除临时表,然后检查它是否有效:
drop table temp_foobar;
select * from foobar;
你应该得到这个,当你检查 foobar 表时,id 列是自动递增 1 并且 id 是主键:
1 one
2 two
3 three