2014-03-27 76 views
0

所以我试图创建我的第一个递归udf(使用MS SQL)去除字符串中不是字母和数字的任何东西。用于删除非字母数字字符的递归SQL UDF

这是由这个帖子的启发(Replace with wildcard, in SQL

CREATE FUNCTION uf_RemoveNonAlphaNumericChar(
        @p_CharIndex int, 
        @p_Value Varchar(max)) 
    RETURNS varchar(max) 
AS 
BEGIN 
    SET @p_CharIndex = PATINDEX('%[^0-9,a-z]%', @p_Value) 
    SET @p_Value = STUFF(@p_Value,@p_CharIndex , 1, SPace(0)) 

    IF @p_CharIndex > 0 
     BEGIN 
     EXEC @p_Value = uf_RemoveNonAlphaNumericChar @p_CharIndex = @p_CharIndex, 
       @p_Value = @p_Value 
     END 
    RETURN @p_Value 
END 

这在我试图分裂,可能是XXX###YYYY分为三个部分字符串更大的问题一步,当某些部件可能失踪。

而我试图做一个没有while循环(该解决方案已经存在,但运行缓慢)。

如果Patindex有一个开始位置(在MS SQL中),我已经完成了。当然,这也不会那么有趣。或作为黄铜填充...

+1

FYI'PATINDEX'可以有一个开始postition:'PATINDEX( '%[^ 0-9,AZ]%',SUBSTRING (@p_Value,2,99999))将开始搜索字符串2的字符串 – JNK

回答

0

我发现了你的问题。你如果连你不觉得它删除符号;在更新的答案) 看:

CREATEFUNCTION uf_RemoveNonAlphaNumericChar(
        @p_CharIndex int, 
        @p_Value Varchar(max)) 
    RETURNS varchar(max) 
AS 
BEGIN 
    SET @p_CharIndex = PATINDEX('%[^0-9,a-z]%', @p_Value) 


    IF @p_CharIndex > 0 
     BEGIN 
     SET @p_Value = STUFF(@p_Value,@p_CharIndex , 1, SPace(0)) 
     EXEC @p_Value = uf_RemoveNonAlphaNumericChar @p_CharIndex = @p_CharIndex, 
       @p_Value = @p_Value 
     END 
    RETURN @p_Value 
END 
+0

你是否试过这个(函数中的'EXEC')? –

-1

它是否必须是递归?

CREATE FUNCTION [dbo].[uf_RemoveNonAlphaNumericChar] 
(
    @val varchar(max) 
) 
RETURNS varchar(1000) 
AS 
BEGIN 
    DECLARE @s VARCHAR(max), @i INT 
    SET @s = @val 

    SET @i = PATINDEX('%[^a-z0-9]%', @s) 
    WHILE @i > 0 
    BEGIN 
     SET @s = REPLACE(@s, SUBSTRING(@s, @i, 1), '') 
     SELECT @i = PATINDEX('%[^a-z0-9]%', @s) 
    END 

    RETURN @s 

END 
+1

这个问题指出,使用while循环的解决方案已经存在,并且他们试图找到一个解决方案而不使用while循环,因为它运行慢。 – JMK

+1

但是使用recursiove函数只会进一步减慢速度。性能方面最好的解决方案将是SQL CLR之一,然后是这一个。 – dean

+0

我需要做的,如果我正确地消化我的研究,修改这个函数的表值,所以我可以使用它与跨应用http://sql-sudhir.blogspot.com/2009/10/use-of- function-in-where-clause.html – discosammy

相关问题