SQL替换WHERE子句

4
我们有以下查询,用于将备忘录字段中的任何 & 替换为HTML等效项(&)。在编写查询时,我们没有考虑到该字段中可能还存在其他以“&”开头的HTML标签(即——"等)。由于我们必须确保所有的和符号在单独使用而不是其他标记的一部分时都是HTML等效项,因此我们必须跳过那些作为其他标记一部分的和符号。话虽如此,似乎可以以 & 开始的最短HTML标记长度为3个字符,最长为六个字符,因此是否有任何更新where子句的想法,以便它不会更新任何在 & 后的4-7个字符中带有“;”的 &?谢谢。
 UPDATE STOCKMEM
 SET INETFDESC = CAST(
                       REPLACE(
                               REPLACE(
                                       CAST(INETFDESC as NVarchar(MAX))
                               ,'&','&')
                       , '&', ,'&')AS NText)
  WHERE INETFDESC LIKE '%&[^amp;]%' 

你考虑过使用正则表达式吗?https://dev59.com/5Gox5IYBdhLWcg3w3X5S - Svek
不确定是否有这个选项,但如果我遇到这个问题,我会使用带有C#脚本任务的SSIS。 - RoundFour
这些事情通常使用编程语言处理比在SQL中更好。 - ATC
3个回答

0

我认为这将完成工作:

 UPDATE STOCKMEM
 SET INETFDESC = CAST(
                 REPLACE(
                     CAST(INETFDESC as NVarchar(MAX)), '& ', '&amp ')
                 ) AS NText
              )

如果&是任何标签的一部分,它将不会被空格跟随,因此请将每个后面跟随空格的&替换为&amp后跟空格。

0

处理这个问题可能不是最佳方法,但...

您可以使用下划线_作为指示器,表明该位置应该有一些字符,这在像这样的情况下有效地将其变为一个字符计数器。 这是一个快速的例子:

SELECT REPLACE('This is &[^amp;] just a test.','&[^amp;]','&')
WHERE 'This is &[^amp;] just a test.' LIKE '%&___;%'

这不会返回任何值,因为WHERE子句中的字符串不包括&后面跟着三个字符___,然后是一个分号。

SELECT REPLACE('This is &[^amp;] just a test.','&[^amp;]','&')
WHERE 'This is &[^amp;] just a test.' LIKE '%&_____;%' 

这将返回一个值,因为WHERE子句中的字符串符合LIKE条件:&_ _ _ _ _;(为了清晰起见添加了空格)

也许你可以利用这个?


0

这不太美观,但我认为它能胜任工作。 思路是找到所有不属于实体的和号。 在这里,实体被假定为和号、一个字母、一些更多字符,然后是分号。

set nocount on
--drop table #HtmlTest
select CONVERT( nvarchar(255) , 
  N'The & & z; HTML & replacement < > é ε test & a; ' )   as test
  into #HtmlTest

select test from #HtmlTest

declare @posStart int, @posStart1 int, @posStart2 int, @posEnd int, @isEntity bit
set @posStart = 1 

while (@posStart != 0)
  begin
    select @posStart1 = charindex('&', test, @posStart + 1)  from #HtmlTest
    select @posStart2 
        = patindex('%&[a-z]%;%', substring(test, @posStart + 1, 99999)) 
        + @posStart    from #HtmlTest
    set    @isEntity  = IIF(@posStart1 = @posStart2, 1, 0)
    select @posEnd    = charindex(';', test, @posStart1 + 1) from #HtmlTest

    set @posStart = @posStart1

    if (@isEntity = 0 and @posStart1 > 0) 
      begin
        update #HtmlTest 
          set test = SUBSTRING(test, 1, @posStart1 - 1) + '&' 
                   + SUBSTRING(test, @posStart1 + 1, 999999) 
        select test from #HtmlTest
        set @posStart += 4
      end
  end
select test from #HtmlTest
set nocount off

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接