Sql server 2008 如何有条件地插入

Sql server 2008 如何有条件地插入,sql-server-2008,insert,duplicates,Sql Server 2008,Insert,Duplicates,我创建了一个临时表tblaccount,上次更新。我有以下两个来自不同来源的插入,可以是来自不同数据库的表,以插入具有上次更新日期的帐户。比如说 create table #tbl ([account] numeric(18, 0), [last_update] datetime) insert into #tbl(account , last_update) select table1.account, max(table1.last_update) from table1 join… gr

我创建了一个临时表tblaccount,上次更新。我有以下两个来自不同来源的插入,可以是来自不同数据库的表,以插入具有上次更新日期的帐户。比如说

create table #tbl ([account] numeric(18, 0), [last_update] datetime)

insert into #tbl(account , last_update)
select table1.account, max(table1.last_update)
from table1 join…
group by table1.account

insert into #tbl(account , last_update)
select table2.account, max(table2.last_update)
from table2 join…
group by table2.account

问题是,这可能会导致表tbl中出现重复帐户。我要么在每次插入时避免它,要么在两次插入后删除重复项。此外,如果有两个不同的帐户上次更新,我希望tbl有最新的上次更新。如何实现此条件插入?哪一个性能更好?

您认为可以将查询重写为以下内容:

create table #tbl ([account] numeric(18, 0), [last_update] datetime)

insert into #tbl(account , last_update)
  select theaccount, MAX(theupdate) from 
  (
    select table1.account AS theaccount, table1.last_update AS theupdate
    from table1 join…
     UNION ALL
    select table2.account AS theaccount, table2.last_update AS theupdate
    from table2 join…
   ) AS tmp GROUP BY theaccount 

UNION ALL将结合table1+table2记录为您构建一个唯一的表。从这里,您可以像一个常规表一样,这意味着您可以使用group by找到每个记录的最大上次更新时间

@GaolaiPeng它是按帐户分组的,而不是按帐户分组的,您可以重试吗?我添加了select theaccount,MAXtheupdate From。。。作为tmp小组的一员,该小组随后开始运作。谢谢你的好主意。每个帐户只有两次插入吗?您是每个帐户只运行一次,还是可以在第二天或一周后再次运行?你签出命令了吗? insert into #tbl(account , last_update) select account, last_update from ( select a.* from #table1 a where last_update in( select top 1 last_update from #table1 b where a.account = b.account order by last_update desc) UNION select a.* from #table2 a where last_update in( select top 1 last_update from #table2 b where a.account = b.account order by last_update desc) ) AS tmp