在SQL中查找并替换所有特殊字符

时间:2015-06-25 12:14:05

标签: sql sql-server sql-server-2008

我想复制新列中的所有行,并用 - 替换所有特殊字符。我的代码如下。

我的桌面设计

enter image description here

 select * from mycode
    UPDATE mycode
    SET newName = Replace(myname, '%[^0-9a-zA-Z]%', '-')

我的代码正在复制,但不会替换特殊字符

结果 enter image description here

2 个答案:

答案 0 :(得分:5)

尝试创建此功能

runApp("dir")

然后执行create function dbo.RemoveSpecialChars (@s varchar(256)) returns varchar(256) with schemabinding begin if @s is null return null declare @s2 varchar(256) set @s2 = '' declare @l int set @l = len(@s) declare @p int set @p = 1 while @p <= @l begin declare @c int set @c = ascii(substring(@s, @p, 1)) if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122 set @s2 = @s2 + char(@c) set @p = @p + 1 end if len(@s2) = 0 return null return @s2 end

UPDATE

答案 1 :(得分:5)

尝试此查询

DECLARE @specialchar varchar(15)
DECLARE @getspecialchar CURSOR
SET @getspecialchar = CURSOR FOR
SELECT DISTINCT poschar 
    FROM   MASTER..spt_values S 
           CROSS APPLY (SELECT SUBSTRING(newName ,NUMBER,1) AS poschar from mycode ) t 
    WHERE  NUMBER > 0 

           AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90 
                     OR ASCII(t.poschar) BETWEEN 97 AND 122 
                     OR ASCII(t.poschar) BETWEEN 48 AND 57)

OPEN @getspecialchar 
FETCH NEXT
FROM @getspecialchar INTO @specialchar 
WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE mycode 
        SET newName =Replace(myname,@specialchar,'')
FETCH NEXT
FROM @getspecialchar INTO @specialchar 
END
CLOSE @getspecialchar 
DEALLOCATE @getspecialchar