我在database1
中有以下3个表create table database1..Table1 (id int ,datestamp datetime)
create table database1..Table2 (id int ,datestamp datetime)
create table database1..Table3(id int ,datestamp datetime)
和database2中的这个表
create table database2..Table1 (id int ,datestamp datetime)
我想用更大的datestamp值更新数据库2的Table1 .datestamp(在database1的3个表之间)
是否有比此查询更好的方法(不使用大小写):
update db2t1
set datestamp=
case when db1t1.datestamp > db1t2.datestamp and db1t1.datestamp > db1t3.datestamp then db1t1.datestamp
when db1t2.datestamp > db1t1.datestamp and db1t2.datestamp > db1t3.datestamp then db1t2.datestamp
else db1t3.datestamp
end
from database2..Table1 db2t1 inner join database1..Table1 db1t1 on db2t1.id=db1t1.id
inner join database1..Table2 db1t2 on db1t1.id=db1t2.id
inner join database1..Table3 db1t3 on db1t1.id=db1t2.id
此查询将在巨大的表格上执行
答案 0 :(得分:0)
也许你可以这样做:
UPDATE db2t1
SET db2t1.datestamp = tbl2.MaxDate
from database2..Table1 db2t1
JOIN
(
SELECT
MAX(tbl.datestamp) AS MaxDate,
tbl.id
FROM
(
SELECT id,datestamp database1..Table1 UNION ALL
SELECT id,datestamp database1..Table2 UNION ALL
SELECT id,datestamp database1..Table3
) AS tbl
GROUP BY
tbl.id
) AS tbl2
ON tbl2.id=db2t1.id
答案 1 :(得分:0)
任何你在大桌面上这样做的方式都很困难。我会将其拆分为批次(基于ID的范围,假设它是聚簇键)并将查询更改为:
UPDATE T1
SET dateStamp = X.dateStamp
FROM database2..Table1 T1
JOIN (SELECT ID, MAX(dateStamp) dateStamp
FROM (
SELECT ID, dateStamp
FROM table2 T2
UNION ALL
SELECT ID, dateStamp
FROM table3 T3
) N
GROUP BY ID) X ON X.ID = T1.ID
WHERE X.dateStamp > T1.dateStamp
要减少T1锁定的时间,可以将派生表放入临时表,然后从结果中更新T1。