How to replace first and last character of column in sql server?

后端 未结 9 2738
名媛妹妹
名媛妹妹 2021-02-19 11:43

I have a database column and its give a string like ,Recovery, Pump Exchange,.

I want remove first and last comma from string.

Expected Result :

相关标签:
9条回答
  • 2021-02-19 12:06

    Use Substring():

    SET @String=SUBSTRING(@String ,2,Len(@String)-2)
    

    SUBSTRING() returns part of an expression.

    Syntax:

    SUBSTRING ( expression ,start , length )
    
    0 讨论(0)
  • 2021-02-19 12:12

    For removing same character you can use below system function TRIM

    Only from 2017

    DECLARE @str VARCHAR(MAX) = '[REMOVE THIS CLOSE BRACKET]'
    
    SELECT TRIM('[]' FROM @str)
    

    But for different character removing you need to use SUBSTRING

    SELECT SUBSTRING(@str,2,LEN(@str)-2)
    
    0 讨论(0)
  • 2021-02-19 12:13

    You can try this way using SUBSTRING to replace first and last character of column in table.

    In this example, I have used double quotes(") instead of comma(,). It will replace only first and last character(“), if the column value starts with double quotes(“) and ended with double quotes(“).

    DECLARE @tblProducts TABLE (ProductName VARCHAR(100))
    
    INSERT INTO @tblProducts VALUES ('"Recovery 10x12" Pump Exchange"')
    INSERT INTO @tblProducts VALUES ('"Recovery Pump Exchange 10x12""')
    INSERT INTO @tblProducts VALUES ('Recovery Pump Exchange 10x12"')
    
    --REPLACE Last Char(")
    UPDATE @tblProducts SET ProductName = SUBSTRING(ProductName, 1, len(ProductName) - 1) FROM @tblProducts WHERE ProductName LIKE '"%' AND ProductName LIKE '%"'
    
    --REPLACE First Char(")
    UPDATE @tblProducts SET ProductName = SUBSTRING(ProductName, 2, len(ProductName) - 1) FROM @tblProducts WHERE ProductName LIKE '"%'
    
    SELECT * FROM @tblProducts
    

    Result:

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