T-SQL trim   (and other non-alphanumeric characters)

后端 未结 5 1584
谎友^
谎友^ 2020-11-30 09:11

We have some input data that sometimes appears with   characters on the end.

The data comes in from the source system as varchar() and our attempts to cast a

5条回答
  •  天涯浪人
    2020-11-30 10:14

    For large datasets I have had better luck with this function that checks the ASCII value. I have added options to keep only alpha, numeric or alphanumeric based on the parameters.

    --CleanType 1 - Remove all non alpanumeric
    --          2 - Remove only alpha
    --          3 - Remove only numeric
    CREATE FUNCTION [dbo].[fnCleanString] (
            @InputString    varchar(8000)
        ,   @CleanType      int 
        ,   @LeaveSpaces    bit 
    )   RETURNS varchar(8000)
    AS 
    BEGIN
    
        -- // Declare variables
        -- ===========================================================
        DECLARE @Length     int
            ,   @CurLength  int = 1
            ,   @ReturnString varchar(8000)=''
    
        SELECT @Length = len(@InputString)
    
        -- // Begin looping through each char checking ASCII value
        -- ===========================================================
        WHILE (@CurLength <= (@Length+1))
        BEGIN
            IF  (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 48 and 57      AND @CleanType in (1,3) )
            or  (ASCII(SUBSTRING(@InputString,@CurLength,1))    between 65 and 90   AND @CleanType in (1,2) )
            or  (ASCII(SUBSTRING(@InputString,@CurLength,1))    between 97 and 122  AND @CleanType in (1,2) )
            or  (ASCII(SUBSTRING(@InputString,@CurLength,1))    = 32    AND @LeaveSpaces = 1 )
            BEGIN
                SET @ReturnString = @ReturnString + SUBSTRING(@InputString,@CurLength,1)
            END
            SET @CurLength = @CurLength + 1
        END
    
        RETURN  @ReturnString
    END
    

提交回复
热议问题