TSQL - 替换或删除两个不同字符串之间的字符串,在整个列的字段中多次

时间:2012-06-22 01:25:37

标签: sql sql-server tsql

我想替换或删除这两个字符之间的所有字符< >它们在整个油田中发生多次,并且在每一行的不同情况下都会发生

我相信要替换的字符串是html所以当我试图发布一个例子时,网站只是将其注册为格式化。

我使用replace来删除所有常见的字符串,例如用于换行符的html,但是有些字段使用十六进制颜色值来改变字段。

谢谢!

4 个答案:

答案 0 :(得分:3)

DECLARE @foo TABLE(TAGS VARCHAR(MAX));
INSERT @foo VALUES('<fname>John</fname><lname>Dewey</lname>');

SELECT 1; --This will initialize @@ROWCOUNT if necessary. Might be optional depending on your query
WHILE @@ROWCOUNT > 0 BEGIN
    UPDATE @foo
    SET TAGS = STUFF(TAGS,CHARINDEX('<',TAGS),CHARINDEX('>',TAGS) - CHARINDEX('<',TAGS) + 1,'')
    WHERE TAGS LIKE '%<%>%'
END
SELECT * FROM @foo;

结果

------------------------
JohnDewey

答案 1 :(得分:1)

CREATE TABLE #html(Value NVARCHAR(MAX))
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>1 <Remove>abc<also remove>def<Take this out>ghi')
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>2 <Remove>abc<also remove>def<Take this out>ghi')
INSERT INTO #html(Value) VALUES('<ShouldBeRemoved>3 <Remove>abc<also remove>def<Take this out>ghi')

;with Cte(Value) AS (
    SELECT Value FROM #html
    UNION ALL
    SELECT REPLACE(Value, SUBSTRING(Value, CHARINDEX('<', Value), CHARINDEX('>', Value) - CHARINDEX('<', Value) + 1),'')
    FROM Cte
    WHERE CHARINDEX('<', Value) != 0
)
SELECT Value FROM Cte
WHERE CHARINDEX('<', Value) = 0
OPTION (MAXRECURSION 0);

DROP TABLE #html

答案 2 :(得分:0)

CREATE FUNCTION [dbo].[udf_RemoveHtmlTag] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
    WHILE((CHARINDEX('<', @HTMLText)>0) and (CHARINDEX('>', @HTMLText)>0))
    Begin
        SET @HTMLText = REPLACE(@HtmlText,SUBSTRING(@HTMLText, CHARINDEX('<', @HTMLText), CHARINDEX('>', @HTMLText) - CHARINDEX('<', @HTMLText) + 1),'');       
    End

    RETURN @HTMLText
END
GO

Then how to use this func

select [dbo].[udf_RemoveHtmlTag]([column_name]) from tablename 

答案 3 :(得分:0)

此代码适用于希望避免调用UDF(用户定义函数)的用户。 假设您的sql表col。包含如下所示的HTML标签,并且您想删除Uncaught ReferenceError: settings is not defined at eval (eval at saferEvalNoReturn (big.ts:3400), <anonymous>:3:21) at saferEvalNoReturn (big.ts:3400) at Component.evaluateCommandExpression (evented.js:172) at runListenerHandler (evented.js:9) at HTMLInputElement.handler <之间的所有内容。 >

步骤1:将结果集存储到临时表中

[Remark] =" the HTML tags like:   < div > < p >< span > We are trying to contact the company (Tel:&nbsp;< /span >< span> < /p > < /div > etc'  "

步骤2::使用以下代码删除<和>之间的所有内容并更新该字段。

select .... into #t1 from....where...blah blah 

第3步:从“温度”表中选择所需的结果

WHILE @@ROWCOUNT > 0 BEGIN
    UPDATE #t1
    SET [Remark] = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(STUFF([Remark],CHARINDEX('<',[Remark]),CHARINDEX('>',[Remark]) - CHARINDEX('<',[Remark]) + 1,'') )), CHAR(9), ' '), CHAR(10), ' '), CHAR(11), ' '), CHAR(12), ' '), CHAR(13), ' '), '&nbsp;', '')))
    WHERE [Remark] LIKE '%<%>%'
END