gpt4 book ai didi

sql-server - 使用多列主键将缺少的行从一个表复制到另一个表

转载 作者:行者123 更新时间:2023-12-04 18:19:55 24 4
gpt4 key购买 nike

本主题与 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

最佳答案

您的查询不正确,因为您的各种条件可以在不同的行上匹配。

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不够?如果不是,它肯定有一个奇怪且不正确的名称。

关于sql-server - 使用多列主键将缺少的行从一个表复制到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10885587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com