2012-06-04 81 views
2

本主题与Copy missing rows from one table to another in sql server with stored procedure有关,但是现在问题稍微复杂一些。使用多列主键将缺少的行从一个表复制到另一个表

我必须在不同的数据库(在同一台服务器上)是相同的表。我需要将左数据库表中的数据行传输到正确的数据库表,但我只想传输不在正确的数据库表中的行。

我的表有四个主键,看到图像

enter image description here

我想用这样的

insert into [EXTERN_EPI6R2].[dbo].[tblBigTableReference] 
select * from [EXTERN].[dbo].[tblBigTableReference] 
where (
pkId not in (select pkId 
    from [EXTERN_EPI6R2].[dbo].[tblBigTableReference]) 
and PropertyName not in (select PropertyName 
    from [EXTERN_EPI6R2].[dbo].[tblBigTableReference]) 
and IsKey not in (select IsKey 
    from [EXTERN_EPI6R2].[dbo].[tblBigTableReference]) 
and [Index] not in (select [Index] 
    from [EXTERN_EPI6R2].[dbo].[tblBigTableReference]) 
) 

但是,这不会工作,因为条件的堆叠是某种程度上是错误的。使用SQL Server 2008 R2

回答

3

您的查询

林是不正确的,因为你的各种条件,可以在不同的行匹配。

insert into [EXTERN_EPI6R2].[dbo].[tblBigTableReference] 
select * from [EXTERN].[dbo].[tblBigTableReference] AS s 
where NOT EXISTS 
(
    SELECT 1 FROM [EXTERN_EPI6R2].[dbo].[tblBigTableReference] AS d 
    WHERE d.pkId = s.pkId 
    AND d.PropertyName = s.PropertyName 
    AND d.IsKey = s.IsKey 
    AND d.[Index] = s.[Index] -- terrible column name 
); 

但这引出了一个问题 - 为什么这些列中的所有四列都是键的一部分? pkId不够?如果不是,它肯定有一个奇怪和不正确的名字。

相关问题