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

前端 未结 8 1264
甜味超标
甜味超标 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:29

    Ideally, you would do this in an application language such as C# + LINQ as mentioned above.

    If you wanted to do it purely in T-SQL though, one way make things neater would be to firstly create a table that held all the punctuation you wanted to removed.

    CREATE TABLE Punctuation 
    (
        Symbol VARCHAR(1) NOT NULL
    )
    
    INSERT INTO Punctuation (Symbol) VALUES('''')
    INSERT INTO Punctuation (Symbol) VALUES('-')
    INSERT INTO Punctuation (Symbol) VALUES('.')
    

    Next, you could create a function in SQL to remove all the punctuation symbols from an input string.

    CREATE FUNCTION dbo.fn_RemovePunctuation
    (
        @InputString VARCHAR(500)
    )
    RETURNS VARCHAR(500)
    AS
    BEGIN
        SELECT
            @InputString = REPLACE(@InputString, P.Symbol, '')
        FROM 
            Punctuation P
    
        RETURN @InputString
    END
    GO
    

    Then you can just call the function in your UPDATE statement

    UPDATE tblMyTable SET FieldName = dbo.fn_RemovePunctuation(FieldName)
    

提交回复
热议问题