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

前端 未结 8 1268
甜味超标
甜味超标 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条回答
  • 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
    
    0 讨论(0)
  • 2021-02-05 21:30

    If it's a one-off thing, I would use a C# + LINQ snippet in LINQPad to do the job with regular expressions.

    It is quick and easy and you don't have to go through the process of setting up a CLR stored procedure and then cleaning up after yourself.

    0 讨论(0)
提交回复
热议问题