大量数据的Update Self Join性能降低

时间:2018-02-12 08:41:26

标签: sql sql-server sql-server-2008

在我的tblAccount中,有3个索引。聚簇索引是“Date,Accnumber,CifNum”。而非群集是“ID1”和“ID2”。我使用内部自联接来检测需要确定为错误的内容,但是存在大量数据并且连接需要很长时间,导致性能降低。可以做些什么来避免这种情况?

我想检查row1 ID1与row2 ID2是否相同,这将是一个错误。

UPDATE t SET ErrorCode = 'Same value of ID1 ID2'
FROM tblAccount t WITH (NOLOCK)
INNER JOIN tblAccount t2 WITH (NOLOCK)
ON t.Date = t2.Date
AND t.CifNum = t2.CifNum
AND t.ID2 = t2.ID1
WHERE t.Date = '20171231'

下面是为同一个CifNum和Date检测到不同的ID1或ID2。

UPDATE t SET t.ErrorCode = (CASE WHEN t.ID1 <> t2.ID1 OR t.ID2 <> t2.ID2 THEN 'Different ID1 or ID2' ELSE NULL END)
FROM tblAccount t WITH (NOLOCK)
INNER JOIN tblAccount t2 WITH (NOLOCK)
ON t.Date = t2.Date 
AND t.CifNum = t2.CifNum
AND (t.ID1 <> t2.ID1 OR t.ID2 <> t2.ID2 )
WHERE t.Date = '20171231'

在这种情况下,小组是否可以通过以下方式获得帮助?

UPDATE t SET ErrorCode = 'Same value of ID1 ID2'
FROM tblAccount t WITH (NOLOCK) 
inner join (select cifnum, ID1, ID2, Date from tblAccount WHERE Date ='20171231' group by cifnum, ID1, ID2, Date) t2
ON t.Date = t2.Date
AND t.CifNum = t2.CifNum
AND t.ID2 = t2.ID1
WHERE t.Date = '20171231'

1 个答案:

答案 0 :(得分:0)

您可以使用它来更新相同的值

UPDATE t SET ErrorCode = 'Same value of ID1 ID2'
FROM tblAccount t 
WHERE EXISTS (
    SELECT * FROM tblAccount t2 
        WHERE t.Date = t2.Date
        AND t.CifNum = t2.CifNum
        AND t.ID2 = t2.ID1)
AND t.Date = '20171231'