删除括号之间的字符

时间:2018-08-29 16:11:00

标签: sql sql-server tsql sql-server-2008-r2

我正在使用SQL Server 2008 R2,但是正在通过SQL Server 2012 Management Studio访问该服务器。

我有一个名为Search的表,其列类型为Body的列(nvarchar(Max), not null)

此列中的数据实际上是电子邮件的正文,并且此列将所有HTML标记保留为文本的一部分。

例如,电子邮件正文将显示:

 Good morning
 This invoice has been assigned.

但是当它存储在名为Body的列中时,它看起来像这样:

[size=14.0pt]Good morning
[/size][size=14.0pt]This invoice has been assigned.[/size] 

我具有以下SQL来删除“ [”和“]”之间的所有内容(包括方括号):

 SELECT 
     *,
     CASE 
        WHEN CHARINDEX('[', Body) > 0 AND CHARINDEX(']', Body) > 0 
             AND CHARINDEX('[', Body) < CHARINDEX(']', Body) 
           THEN STUFF(Body, CHARINDEX('[', Body), (CHARINDEX(']', Body) - CHARINDEX('[', Body)) + 1, '')
           ELSE Body
     END AS Body1
FROM search

但是所有这些都是删除现在看起来像这样的第一组标签:

Good morning
[/size][size=14.0pt]This invoice has been assigned.[/size]

您能为我提供SQL方面的帮助吗,以便将其全部删除,所以它看起来像这样:

Good Morning
This invoice has been assigned.

1 个答案:

答案 0 :(得分:1)

您可以定义一个标量函数,以删除方括号及其之间的所有文本:

create function [dbo].[fx_removetags] (@text nvarchar(max))
    returns nvarchar(max) as
begin
    declare @tag_start  int
    declare @tag_end    int
    declare @tag_length int
    set @tag_start = charindex('[', @text)
    set @tag_end = charindex(']', @text, charindex('[', @text))
    set @tag_length = (@tag_end - @tag_start) + 1
    while @tag_start > 0 and @tag_end > 0 and @tag_length > 0
        begin
            set @text = stuff(@text,@tag_start,@tag_length, '')
            set @tag_start = charindex('[',@text)
            set @tag_end = charindex(']',@text,charindex('[', @text))
            set @tag_length = (@tag_end - @tag_start) + 1
        end
    return ltrim(rtrim(@text))
end

现在您可以调用该函数以获取不带括号的文本:

declare @test nvarchar(max)= ''
set @test = '[size=14.0pt]Good morning [/size][size=14.0pt]This invoice has been assigned.[/size] '

select [dbo].[fx_RemoveTags](@test)

结果:

enter image description here

在特定情况下,您可以使用以下功能:

SELECT 
     *,
     [dbo].[fx_RemoveTags](@test) as Body1
FROM search