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' 

PRIMARY KEY約束--Violation。不能在對象'A.table'中插入重複鍵。

我已經嘗試

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

我使用的是SQL Server 2005中

回答

0

的主鍵衝突是告訴你,在A.tablecustomer_key值的至少一個你正嘗試從B.Table插入已用於A中的其他客戶記錄(並且假定您已經爲此customer_code運行了刪除語句)。

這意味着現在考慮試圖保持兩個表A和B之間的代理標識列customer_key同步已經太遲了(正如您所說的,您不是在截斷A並從頭開始複製B,如果適用的話)。但是,似乎customer_code不提供客戶的唯一標識(idempotence)(因爲刪除刪除了10行)。

因此,在總結 - 如果你不需要建立任何其他鏈接比customer_code,並有可能通過customer_name,您可以複製數據到A將被分配新的身份customer_key的:

(即離開IDENTITY_INSERT OFF)

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' 
+0

東西必須在這裏給。您可能需要刪除'A..Customer'表上的所有數據並從頭開始重新插入(在這種情況下,您最好放棄'A..Customer'上的標識,因爲它是從'B'驅動的)否則你需要承認不可能將數據合併到'A'中,並且保留'B'的代理id的值與'A'的密鑰相同,除非你將PK放在A上並允許重複。 – StuartLC