我有一个表,其中包含带有占位符的文本字段。像这样的事情:
Row Notes
1. This is some notes ##placeholder130## this ##myPlaceholder##, #oneMore#. End.
2. Second row...just a ##test#.
(该表平均包含约 1-5k 行。一行中占位符的平均数量为 5-15)。
现在,我有一个如下所示的查找表:
Name Value
placeholder130 Dog
myPlaceholder Cat
oneMore Cow
test Horse
(查找表将包含 10k 到 100k 条记录)
我需要找到最快的方法将这些占位符从字符串连接到查找表并替换为值。所以,我的结果应该如下所示(第一行):
This is some notes Dog this Cat, Cow. End.
我想到的是将每个占位符的每一行拆分为多个,然后将其连接到查找表,然后将记录连接回具有新值的原始行,但平均需要大约 10-30 秒。
最佳答案
您可以尝试使用数字表拆分字符串,然后使用 for xml 路径
重建它。
select (
select coalesce(L.Value, T.Value)
from Numbers as N
cross apply (select substring(Notes.notes, N.Number, charindex('##', Notes.notes + '##', N.Number) - N.Number)) as T(Value)
left outer join Lookup as L
on L.Name = T.Value
where N.Number <= len(notes) and
substring('##' + notes, Number, 2) = '##'
order by N.Number
for xml path(''), type
).value('text()[1]', 'varchar(max)')
from Notes
我借用了 this blog post by Aaron Bertrand 的字符串分割
关于sql - 用 join 替换 varchar(max) 字段中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436644/