SQL Server: How do you remove punctuation from a field?

前端 未结 8 1269
甜味超标
甜味超标 2021-02-05 20:50

Any one know a good way to remove punctuation from a field in SQL Server?

I\'m thinking

UPDATE tblMyTable SET FieldName = REPLACE(REPLACE(REPLACE(FieldNa         


        
8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 21:30

    I took Ken MC's solution and made it into an function which can replace all punctuation with a given string:

    ----------------------------------------------------------------------------------------------------------------
    -- This function replaces all punctuation in the given string with the "replaceWith" string
    ----------------------------------------------------------------------------------------------------------------
    IF object_id('[dbo].[fnReplacePunctuation]') IS NOT NULL
    BEGIN
        DROP FUNCTION [dbo].[fnReplacePunctuation];
    END;
    GO
    CREATE FUNCTION [dbo].[fnReplacePunctuation] (@string NVARCHAR(MAX), @replaceWith NVARCHAR(max))
    RETURNS NVARCHAR(MAX)
    BEGIN
        DECLARE @Result Varchar(max) = @string;
        DECLARE @BadChars Varchar(12) = '%[^a-z0-9]%'; -- to leave spaces - SELECT @BadChars = '%[^a-z0-9] %'
        DECLARE @p int = PatIndex(@BadChars,@Result);
        DECLARE @searchFrom INT;
        DECLARE @indexOfPunct INT = @p;
    
        WHILE @indexOfPunct > 0 BEGIN
          SET @searchFrom = LEN(@Result) - @p;
          SET @Result = Left(@Result, @p-1) + @replaceWith + Substring(@Result, @p+1,LEN(@Result));
          SET @IndexOfPunct = PatIndex(@BadChars, substring(@Result, (LEN(@Result) - @SearchFrom)+1, LEN(@Result)));
          SET @p = (LEN(@Result) - @searchFrom) + @indexOfPunct;
        END
        RETURN @Result;
    END;
    GO
    -- example:
    SELECT dbo.fnReplacePunctuation('This is, only, a tést-really..', '');
    

    Output:

    Thisisonlyatéstreally
    

提交回复
热议问题