【问题标题】:SQL replace WHERE clauseSQL 替换 WHERE 子句
【发布时间】:2017-07-11 23:45:24
【问题描述】:

我们有下面的查询,它被编写来用 HTML 等价物 (&) 替换备忘录字段中的任何 &。在编写时,我们没有考虑到字段中可能存在其他以“&”开头的 HTML 标记(即 — “等)。因为我们必须确保所有 & 符号在单独使用时是 HTML 等价的,而不是另一个的一部分标记我们必须跳过那些在另一个标记的一部分。也就是说,可以以 & 开头的最短 HTML 标记似乎是 3 个字符,最长的似乎是 6 个字符,所以 & _ _ _ ; 到 & _ _ _ _ _ _ ; 长...有什么想法可以更新 where 子句,这样它就不会更新在 & 之后的接下来的 4-7 个字符中以“;”开头的任何 &?谢谢。

 UPDATE STOCKMEM
 SET INETFDESC = CAST(
                       REPLACE(
                               REPLACE(
                                       CAST(INETFDESC as NVarchar(MAX))
                               ,'&','&')
                       , '&', ,'&')AS NText)
  WHERE INETFDESC LIKE '%&[^amp;]%' 

【问题讨论】:

标签: sql sql-server sql-server-2014


【解决方案1】:

可能不是处理此问题的最佳方法,但是...

您可以使用下划线_ 指示该位置应该有一些字符,这在这种情况下有效地使其成为字符计数器。只是一个简单的例子:

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 条件:&_ _ _ _ _;(为清楚起见添加了间距)

也许你可以利用它来发挥你的优势?

【讨论】:

    【解决方案2】:

    这并不漂亮,但我认为它确实有效。 这个想法是找到不属于实体的所有&符号。 在这里,实体被假定为 & 符号,一个字母,更多字符,然后是半列。

    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
    

    【讨论】:

      【解决方案3】:

      我认为这可以完成工作:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 2014-10-30
        • 2023-03-31
        相关资源
        最近更新 更多