替换SQL搜索结果中的几个关键字

时间:2018-11-28 01:04:31

标签: sql sql-server

已从表中选择带有varchar字符串的列。 为了显示目的,有些特殊字符需要替换。 最好的方法是什么?

select top (1) timestamp, url from dbo.transcationtable

和事务表包含的URL包含%20,%22等,用于空格和其他字符。 需要用物理空间和其他符号代替它们

1 个答案:

答案 0 :(得分:1)

您正在寻找UrlDecode,可以尝试编写函数。

CREATE FUNCTION dbo.UrlDecode(@url varchar(3072))
RETURNS varchar(3072)
AS
BEGIN 
    DECLARE @count int, @c char(1), @cenc char(2), @i int, @urlReturn varchar(3072) 
    SET @count = Len(@url) 
    SET @i = 1 
    SET @urlReturn = '' 
    WHILE (@i <= @count) 
     BEGIN 
        SET @c = substring(@url, @i, 1) 
        IF @c LIKE '[!%]' ESCAPE '!' 
         BEGIN 
            SET @cenc = substring(@url, @i + 1, 2) 
            SET @c = CHAR(CASE WHEN SUBSTRING(@cenc, 1, 1) LIKE '[0-9]' 
                                THEN CAST(SUBSTRING(@cenc, 1, 1) as int) 
                                ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 1, 1)))-55 as int) 
                            END * 16 + 
                            CASE WHEN SUBSTRING(@cenc, 2, 1) LIKE '[0-9]' 
                                THEN CAST(SUBSTRING(@cenc, 2, 1) as int) 
                                ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 2, 1)))-55 as int) 
                            END) 
            SET @urlReturn = @urlReturn + @c 
            SET @i = @i + 2 
         END 
        ELSE 
         BEGIN 
            SET @urlReturn = @urlReturn + @c 
         END 
        SET @i = @i +1 
     END 
    RETURN @urlReturn
END
GO

使用方式

Select top (1) timestamp, UrlDecode(url) from dbo.transcationtable

sqlfiddle

引用链接:

http://sqlblog.com/blogs/peter_debetta/archive/2007/03/09/t-sql-urldecode.aspx