Domanda

So I'm trying to create my first recursive udf (using MS SQL) to strip anything that's not letters and numbers from a string.

This was inspired by this post (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

This is one step in a bigger problem where I'm trying to split a string that could be XXX###YYYY into three parts when some of the parts may be missing.

And I'm trying to do it without a while loop (that solution already exists but runs slow).

if Patindex had a start position (in MS SQL), I would already be done. Of course, it would also not be as much fun. Or as cuss-filled...

È stato utile?

Soluzione

I found yours problem. You removing symbol if even you dont find it ;) Look at updated answer:

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

Altri suggerimenti

Does it have to be recursion?

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top