SQL Server百万级数据下游标文本替换的高效优化方案咨询
高效替代SQL Server游标的文本注入方案?
场景说明
我正在使用SQL Server,现有一张存储文本注入规则的表,其中iBegin为文本中需注入标记的起始位置,iEnd为结束位置。
举个例子:
原文本:
Hello how are you today
当注入规则为iBegin = 3、iEnd = 7且xStatus为CopyRights时,会在对应位置的前后添加版权符号,处理后结果为:
Hel©lo h©ow are you today
数据源示例
规则表数据如下:
| ID | iRepID | xStatus | iBegin | iEnd |
|---|---|---|---|---|
| 1 | 1001 | Registered | 4 | 6 |
| 2 | 1001 | CopyRights | 9 | 15 |
| 3 | 1001 | Hat | 18 | 22 |
| 4 | 2002 | CopyRights | 2 | 7 |
| 5 | 2002 | Registered | 4 | 11 |
| 6 | 2002 | Dollar | 15 | 18 |
处理效果示例
RepID 1001
原文本:This is a test report, will be used for testing处理后结果:
This® i®s a© test ©rep^ort,^ will be used for testingRepID 2002
原文本:Hi There, Hope you had a good day. Pray for Gaza.处理后结果:
Hi© T®her©e, H®ope $you$ had a good day. Pray for Gaza.
现有游标实现
我当前用游标实现了这个逻辑,但效率很低,代码如下:
DECLARE db_cursor CURSOR FOR SELECT iRepID, xStatus, iBegin, iEnd WHERE iRepID = 1001 OPEN db_cursor FETCH NEXT FROM db_cursor INTO @iRepID, @xStatus, @iBegin, @iEnd WHILE @@FETCH_STATUS = 0 BEGIN SET @Mark = CASE @xStatus WHEN 'Registered' THEN '®' WHEN 'CopyRights' THEN '©' WHEN 'Hat' THEN '^' WHEN 'Dollar' THEN '$' END SET @RepSub = @Mark + ISNULL(SUBSTRING(@RepText, @iBegin, @iEnd-@iBegin + 1), '') + @Mark SET @RepText = ISNULL(LEFT(@RepText, @iBegin - 1), '') + @RepSub + ISNULL(SUBSTRING(@RepText, @IEnd+1, @RepLen), '') FETCH NEXT FROM db_cursor INTO @iRepID, @xStatus, @iBegin, @iEnd END CLOSE db_cursor DEALLOCATE db_cursor
(注:原代码缺少Dollar分支,已根据示例补充)
问题
由于该脚本要处理百万级行的表,当前游标方案效率极低,请问有没有更高效的替代实现方式?
内容的提问来源于stack exchange,提问作者asmgx
相关产品推荐
相关产品推荐

