TSQL如何在字符串中查找父项?
我有一个字符串:TSQL如何在字符串中查找父项?,tsql,Tsql,我有一个字符串: '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]' 'This is some random text so you don't get upset and ' 是否可以使用TSQL查找并替换[text]字符串 结果是: 'This is some random
'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]'
'This is some random text so you don't get upset and '
是否可以使用TSQL查找并替换[text]字符串
结果是:
'This is some random text so you don't get upset '
还是这根绳子
'This is some random text so you don't get upset [me] and [123]'
'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' , '=' )
我建议对……做一些轻微的修改。。。只需将
替换为[
和]
:
CREATE FUNCTION [dbo].[udf_StripTag]
(@TagText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('[',@TagText)
SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
SET @Length = (@End - @Start) + 1
WHILE (@Start > 0
AND @End > 0
AND @Length > 0)
BEGIN
SET @TagText = STUFF(@TagText,@Start,@Length,'')
SET @Start = CHARINDEX('[',@TagText)
SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@TagText))
END
GO
我刚刚注意到这个函数使用VARCHAR而不是NVARCHAR。这太糟糕了,你不应该使用VARCHAR。