4

我有一个这样的sql更新语句

UPDATE t1 SET t1.Field = t2.Field
FROM Table1 as t1
INNER JOIN Table2 as t2 on t1.Key = t2.Key
WHERE t2.FilterField = 'abc'

where 子句使得没有行被更新,该语句运行 30 分钟。(该表有 5000 万行)

如果我将语句更改为有什么奇怪的

SELECT t1.Field, t2.Field
FROM Table1 as t1
INNER JOIN Table2 as t2 on t1.Key = t2.Key
WHERE t2.FilterField = 'abc'

几乎立即返回一个空的结果集

如果我将声明更改为

UPDATE t1 SET t1.Field = 1
FROM Table1 as t1

它会在大约 3 秒内更新表格。

我真的很困惑 SQL Server 在没有更新任何记录的更新语句上阻塞了什么。

4

2 回答 2

2

我们最近有类似的事情,我们的解决方案是:

UPDATE t1 SET t1.Field = t2.Field
FROM (SELECT DISTINCT Table1 as t1
INNER JOIN Table2 as t2 on t1.Key = t2.Key
WHERE t2.FilterField = 'abc') t3
WHERE t1.key = t3.key

其中 key 是某种形式的唯一性。对我们来说,导致问题的是订购。所以另一种选择是索引。这使我们的 6 小时查询缩短到大约一分钟。

于 2016-11-21T22:17:14.757 回答
0

如果时间不是问题,您可以创建单独的更新语句来运行,就像这样,看看会发生什么:

SELECT 'UPDATE Table1 SET Field = ' + CAST(t2.Field as varchar(max)) + ' WHERE Key = ' + CAST(t1.[Key] as varchar(max))
FROM Table1 as t1
INNER JOIN Table2 as t2 on t1.[Key] = t2.[Key]
WHERE t2.FilterField = 'abc'
于 2013-04-18T00:06:43.513 回答