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

后端 未结 5 1576
谎友^
谎友^ 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:06

    This will remove all non alphanumeric chracters

    CREATE FUNCTION [dbo].[fnRemoveBadCharacter]
    (
        @BadString nvarchar(20)
    )
    RETURNS nvarchar(20)
    AS
    BEGIN
    
                DECLARE @nPos INTEGER
                SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)
    
                WHILE @nPos > 0
                BEGIN
                            SELECT @BadString = STUFF(@BadString, @nPos, 1, '')
                            SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)
                END
    
                RETURN @BadString
    END
    

    Use the function like:

    UPDATE TableToUpdate
    SET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate)
    WHERE whatever
    

提交回复
热议问题