如何使用 SQL 中的最新数据更新另一个表? [英] How to update another table with the most recent data in SQL?

查看:22
本文介绍了如何使用 SQL 中的最新数据更新另一个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 DB2 中 Table2 中的数据更新 DB1 中的 Table1.我可以连接并将数据从 DB2 Table2 获取到 DB1 Table1,但我遇到的问题是从 DB2 Table2 获取最近的数据.

I'm trying to update Table1 in DB1 with data from Table2 in DB2. I can connect and get the data from DB2 Table2 into DB1 Table1, but the issue I'm having is getting the MOST RECENT data from DB2 Table2.

我正在查看 DB2 中的 3 个字段:f1、f2 和 &f3.f1 包含重复项(并且是我从 DB1 Table1 匹配的地方),f3 是一个日期字段,我想获取最近的日期来更新 DB1 Table1.以下是我一直在使用的一些代码:

I'm looking at 3 fields in DB2: f1, f2, & f3. f1 contains duplicates (and is where I'm matching from DB1 Table1) and f3 is a date field and I want to grab the most recent date to update DB1 Table1. Below is some of the code I've been using:

Update Table1
Set f2 = c.f2, 
    f3 = convert(varchar, c.f3, 101) 
From Table1 b 
    inner join Server.DB.dbo.Table2 c on b.f1 = c.f1
Where b.f1 = c.f1 

样本数据:

c.f1    c.f2         c.f3
8456    RS47354      06/30/2009
8456    M101021      10/31/2009 (want this one)
7840    5574         NULL
7840    RH013057     06/30/2010 (want this one)
7650    RS48100      06/30/2007
7650    RS49010      06/30/2009 (want this one)

b.f1        b.f2         b.f3
8456        Null         Null
7840        Null         Null
7650        Null         Null

最终,这将设置在 SSIS 包中.

Eventually, this will be set inside an SSIS package.

感谢所有帮助!

-JFV

推荐答案

我不确定这是否是世界上的禁食代码,这显然取决于两个服务器的距离以及每个服务器中的数据量表.

I'm not sure if this is the fasted code in the world, it obviously depends on how close the two servers are and how much data you have in each table.

UPDATE Table1
SET 
    f2 = T2.f2, 
    f3 = convert(varchar, T2.f3, 101) 
FROM 
    Table1 T1
INNER JOIN 
    Server.DB.dbo.Table2 T2
ON 
    T1.f1 = T2.f1
WHERE 
    T2.f3 = (SELECT MAX(f3) FROM Server.DB.dbo.Table2 WHERE f1 = T1.f1)

另一种方法(如果您有足够的控制权)是在 Table2 上创建一个触发器,它会在更新时将最新版本放入临时表中.

An alternative (if you have that much control) is to create a trigger on Table2 which puts the latest version into a temporary table whenever it is updated.

更新:更正了代码.

这篇关于如何使用 SQL 中的最新数据更新另一个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆