0

我想从 B 服务器的 A 服务器中的表中插入数据。

前任:

select count(*) from A.table
-- 100 rows affected


delete from A.table where customer_code = '100'
-- 10 rows affected

select count(*) from B.table
-- 200 rows affected

select count(*) from B.table where customer_code='100'
-- 20 rows affected

both the tables have identity(1,1) and primary_key


insert into A.table(customer_key,customer_code,custome_name)
select customer_key,customer_code,custome_name  
    from B.table where customer_code='100'

--违反主键约束。无法在对象“A.table”中插入重复键。

我已经试过了

SET IDENTITY_INSERT <> ON
DBCC CHECKIDENT(<>, RESEED,0)

我正在使用 SQL Server 2005。

4

1 回答 1

0

主键违规告诉您,您尝试从中插入的customer_keyin的至少一个值已用于不同的 Customer 记录 in (并假设您已经为此运行了 delete 语句)。A.tableB.TableAcustomer_code

这意味着考虑尝试使代理标识列customer_key在两个表 A 和 B 之间保持同步已经为时已晚(正如您所说,如果适用,您无法A从头开始截断和复制B)。但是,似乎customer_code也不提供客户的唯一标识(幂等性)(因为删除删除了 10 行)。

总而言之 - 如果您不需要建立除 bycustomer_code和可能的任何链接之外的任何链接 via customer_name,您可以将数据复制到A其中将被分配新的 identitycustomer_key的:

(即离开IDENTITY_INSERT

insert into A.table(customer_code,custome_name)
select customer_code,customer_name  
    from B.table where customer_code='100'

否则,如果您确实需要唯一标识表之间的行,则需要为 2 个表之间的链接添加新存储。一种快速而肮脏的方法是将 B 的代理直接添加到 A,如下所示:

ALTER TABLE A.table ADD customer_key_TableB INT NULL  -- Or whatever the type of `customer_key`
GO

然后像这样插入并链接数据(同样,IDENTITY INSERT对于表 A 仍然关闭):

insert into A.table(customer_code, customer_name, customer_key_TableB)
select customer_code, customer_name, customer_key
    from B.table where customer_code='100'
于 2013-01-23T10:15:23.030 回答