我有一个字符串:
'This is some random text so you don't get upset [rethink]'
或者这个字符串
'This is some random text so you don't get upset [me] and [123]'
是否可以使用 TSQL 查找和替换 [text] 字符串?
结果:
'This is some random text so you don't get upset '
或者这个字符串
'This is some random text so you don't get upset and '
编辑:
我已经修改了接受的答案,使函数更加动态:
CREATE FUNCTION [dbo].[StripTagWithChar]
(@TagLeft NVARCHAR(1),@TagText NVARCHAR(MAX),@TagRight NVARCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX(@TagLeft,@TagText)
SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
SET @Length = (@End - @Start) + 1
WHILE (@Start > 0
AND @End > 0
AND @Length > 0)
BEGIN
SET @TagText = STUFF(@TagText,@Start,@Length,'')
SET @Start = CHARINDEX(@TagLeft,@TagText)
SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
SET @Length = (@End - @Start) + 1
END
RETURN Replace(LTRIM(RTRIM(@TagText)),' ',' ')
END
现在这个函数接受括号作为输入:
select [dbo].[StripTagWithChar]( '{' , 'this is {not} awesome' , '}' )
最酷的是,现在它将过滤带有相同括号的标签,如下所示:
select [dbo].[StripTagWithChar]( '=' , 'this is =not= awesome' , '=' )