sql – 使用join替换varchar(max)字段中的值

前端之家收集整理的这篇文章主要介绍了sql – 使用join替换varchar(max)字段中的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含带有占位符的文本字段的表.这样的事情
  1. Row Notes
  2. 1. This is some notes ##placeholder130## this ##myPlaceholder##,#oneMore#. End.
  3. 2. Second row...just a ##test#.

(此表平均包含大约1-5k行,一行的占位符平均数为5-15).

现在,我有一个查找表,如下所示:

  1. Name Value
  2. placeholder130 Dog
  3. myPlaceholder Cat
  4. oneMore Cow
  5. test Horse

(查找表将包含从10k到100k记录的任何地方)

我需要找到将这些占位符从字符串加入查找表并用值替换的最快方法.所以,我的结果应该是这样(第1行):

This is some notes Dog this Cat,Cow. End.

我想出的是为每个占位符将每行拆分为多个,然后将其加入查找表,然后将其连接到具有新值的原始行,但平均大约需要10-30秒.

解决方法

我第二个评论说,tsql不适合这个操作,但是如果你必须在db中这样做是一个使用函数来管理多个替换语句的例子.

由于您在每个音符(5-15)和非常大量的令牌(10k-100k)中具有相对较少的令牌,因此我的函数首先从输入中提取令牌作为潜在的令牌,并使用该集合来加入查找( dbo.Token下).在每个音符中查找您的任何令牌的发生情况太多了.

我做了一些perf测试,使用50k的令牌和5k的笔记,这个功能运行得很好,在< 2秒(在笔记本电脑上)完成.请报告此策略对您的影响. 注意:在您的示例数据中,令牌格式不一致(## _#,## _ ##,#_#),我猜这只是一个打字错误,并假定所有令牌采用## TokenName ##的形式.

  1. --setup
  2. if object_id('dbo.[Lookup]') is not null
  3. drop table dbo.[Lookup];
  4. go
  5. if object_id('dbo.fn_ReplaceLookups') is not null
  6. drop function dbo.fn_ReplaceLookups;
  7. go
  8.  
  9. create table dbo.[Lookup] (LookupName varchar(100) primary key,LookupValue varchar(100));
  10. insert into dbo.[Lookup]
  11. select '##placeholder130##','Dog' union all
  12. select '##myPlaceholder##','Cat' union all
  13. select '##oneMore##','Cow' union all
  14. select '##test##','Horse';
  15. go
  16.  
  17. create function [dbo].[fn_ReplaceLookups](@input varchar(max))
  18. returns varchar(max)
  19. as
  20. begin
  21.  
  22. declare @xml xml;
  23. select @xml = cast(('<r><i>'+replace(@input,'##','</i><i>')+'</i></r>') as xml);
  24.  
  25. --extract the potential tokens
  26. declare @LookupsInString table (LookupName varchar(100) primary key);
  27. insert into @LookupsInString
  28. select distinct '##'+v+'##'
  29. from ( select [v] = r.n.value('(./text())[1]','varchar(100)'),[r] = row_number() over (order by n)
  30. from @xml.nodes('r/i') r(n)
  31. )d(v,r)
  32. where r%2=0;
  33.  
  34. --tokenize the input
  35. select @input = replace(@input,l.LookupName,l.LookupValue)
  36. from dbo.[Lookup] l
  37. join @LookupsInString lis on
  38. l.LookupName = lis.LookupName;
  39.  
  40. return @input;
  41. end
  42. go
  43. return
  44.  
  45. --usage
  46. declare @Notes table ([Id] int primary key,notes varchar(100));
  47. insert into @Notes
  48. select 1,'This is some notes ##placeholder130## this ##myPlaceholder##,##oneMore##. End.' union all
  49. select 2,'Second row...just a ##test##.';
  50.  
  51. select *,dbo.fn_ReplaceLookups(notes)
  52. from @Notes;

返回:

  1. Tokenized
  2. --------------------------------------------------------
  3. This is some notes Dog this Cat,Cow. End.
  4. Second row...just a Horse.

猜你在找的MsSQL相关文章