我有一个带有单个IDENTITY
列的表Temp_Identity
。
当我们进行复制时,会正确地复制此表中的数据。但它目前的身份并没有被复制。
这意味着,生产数据库中该表的当前标识为10。但在复制数据库中,它仍然是1。
有没有什么方法可以在不手动的情况下自动解决这个问题?
表结构
CREATE TABLE Temp_Identity
(
ID Int IDENTITY(1,1) Primary Key,
Name Varchar(100)
)
当我在生产数据库中插入以下值时,它在复制数据库中正确生效
INSERT INTO Temp_Identity
SELECT 'AA'
UNION ALL
SELECT 'BB'
UNION ALL
SELECT 'CC'
当我从复制数据库中插入给定的行时,我得到了一个错误。
INSERT INTO Temp_Identity
SELECT 'DD'
这是因为,在复制数据库中,该表包含这三行。当我们进行上述插入时,ID列的值为"1"(生产数据库中该表的当前标识为3。但在复制DB中为1。它应该与生产数据库相同(。它已存在于表中。因此引发了主键错误。
这种方法可能适用于这种情况。
create table tmptbl (ID int identity(1,1) Primary key clustered, name varchar(100))
insert into tmptbl
Select 'A' union all
Select 'B' union all
Select 'C'
创建备份表
create table tmptbl_BCK (ID int identity(1,1) Primary key clustered, name varchar(100))
insert into tmptbl_BCK
select name from tmptbl
delete from tmptbl_BCK --to create the scenario this will remove the previous identity keys and create new keys for new insert.
insert into tmptbl_BCK
select name from tmptbl
select * from tmptbl (in original table)
ID name
1 A
2 B
3 C
select * from tmptbl_BCK
ID name
10 A
11 B
12 C
您可以借助"设置标识插入"选项来确保在这些表中具有相同的标识。首先确保删除行。
delete from tmptbl_BCK
set identity_insert tmptbl_BCK On
insert into tmptbl_BCK (ID, Name) select ID, name from tmptbl
set identity_insert tmptbl_BCK Off
select * from tmptbl_BCK
Output you get:
ID name
1 A
2 B
3 C
现在,若您希望(在复制表中(具有与生产相同的标识值,那个么您可以采用这种方式。
Declare @reseedvalue int = (Select IDENT_CURRENT('tmptbl')) --though it gives you the last inserted value, next time it reseeds it will be 4 in your production table and replication table
--select @reseedvalue
--to reseed based on your production table
DBCC CHECKIDENT ('tmptbl_BCK', RESEED, @reseedvalue)
--test if it creates 4 in your back up table
insert into tmptbl_BCK
select 'D'
select * from tmptbl_BCK