首页 > 解决方案 > 在 SQL Server 中替换/更新表行 [批量数据] 的字符串时性能很慢

问题描述

我想用虚拟数据更新下面称为下面formatted body的主表的列-postsschema

在此处输入图像描述

现在,我想replace/update a substring[ie sourcewith the final URL] 来自上述 formattedbody 列。[ 5335excel 表中的总记录]

在此处输入图像描述

对于我在下面的查询中写的相同 -

DECLARE @LoopCounter INT = 1
DECLARE @SURL nvarchar(max)
DECLARE @FURL nvarchar(max)
WHILE ( @LoopCounter <= 5335)
BEGIN
    SET @SURL = (select sourceURL from temptable where ID = @LoopCounter)
    SET @FURL = (select [TargetURL] from temptable where ID = @LoopCounter)
update posts
Set FormattedBody=REPLACE(CAST(FormattedBody as NVarchar(Max)),@SURL,@FURL)
Where SectionID = 95 and postlevel=1 and CAST(FormattedBody as NVarchar(Max)) like '%' + @SURL + '%'              
    SET @LoopCounter  = @LoopCounter  + 1
END

temptable包含 excel 工作表的数据[i.e. ID,sourceURL, and TargetURL]

上面的查询按预期工作,但是performance is too low, 因为它循环遍历来自 posts 表 [huge data] 的所有行以获取5335记录。

目前,它仅更新 3 条记录/分钟。

任何建议/帮助表示赞赏!:) 谢谢!

标签: sqlsql-serverperformancesql-update

解决方案


我认为您不需要使用whileand update,我会使用andUPDATE .. JOIN代替 。whileupdate

temptable如果和表之间没有任何关系posts,您可以使用CROSS JOIN(笛卡尔积)让每个sourceURL[TargetURL] temptable列映射到posts表然后更新。

UPDATE p
SET FormattedBody = REPLACE(CAST(FormattedBody as NVarchar(Max)),sourceURL,[TargetURL])
FROM posts p
CROSS JOIN 
(
    SELECT sourceURL,[TargetURL]
    FROM temptable 
    where id <= 5335
) targetDt
Where p.SectionID = 95 and p.postlevel=1  

推荐阅读