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

后端 未结 9 2729
名媛妹妹
名媛妹妹 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 11:53
    SELECT LEFT(RIGHT(',Recovery, Pump Exchange,',LEN(',Recovery, Pump Exchange,')-1),LEN(',Recovery, Pump Exchange,')-2)
    
    0 讨论(0)
  • 2021-02-19 11:54

    Alternatively to dasblinkenlight's method you could use replace:

    DECLARE @words VARCHAR(50) = ',Recovery, Pump Exchange,'
    SELECT REPLACE(','+ @words + ',',',,','')
    
    0 讨论(0)
  • 2021-02-19 11:54

    Try like this:

    if(Substring(@mykeyword, 1,1) = ',' and Substring(@mykeyword, LEN(@mykeyword) - 1, LEN(@mykeyword))=',')
    SET @mykeyword = Substring(@mykeyword, 2, LEN(@mykeyword) - 2)
    
    0 讨论(0)
  • 2021-02-19 11:55

    This is an old post but I've decided to add my solution as it will remove the first and last commas of a comma separated string without removing the other commas and also will work with strings that don't start with a comma:

    DECLARE @words VARCHAR(50) = ',Recovery, Pump Exchange,'
    SELECT REPLACE(SUBSTRING(@words , 1, 1),',','') + SUBSTRING(@words, 2, LEN(@words)-2) + REPLACE(SUBSTRING(@words, LEN(@words), 1), ',', '')
    
    0 讨论(0)
  • 2021-02-19 11:56

    You can use SUBSTRING for that:

    SELECT
        SUBSTRING(col, 2, LEN(col)-2)
    FROM ...
    

    Obviously, an even better approach would be not to put leading and trailing commas there in the first place, if this is an option.

    I want to remove last and first comma only if exist otherwise not.

    The expression becomes a little more complex, but the idea remains the same:

    SELECT SUBSTRING(
        col
    ,  CASE LEFT(@col,1) WHEN ',' THEN 2 ELSE 1 END
    ,  LEN(@col) -- Start with the full length
                 -- Subtract 1 for comma on the left
          - CASE LEFT(@col,1) WHEN ',' THEN 1 ELSE 0 END 
                 -- Subtract 1 for comma on the right
          - CASE RIGHT(@col,1) WHEN ',' THEN 1 ELSE 0 END
    )
    FROM ...
    
    0 讨论(0)
  • 2021-02-19 11:57

    Using LEN could backfire because LEN ignores trailing spaces. These could be added because of ANSI_PADDING defaulting to ON. So, you'd need RTRIM.

    For completeness, I've added LTRIM too...

    REVERSE(SUBSTRING(REVERSE(RTRIM(LTRIM(SUBSTRING(MyCol, 2, 8000)))), 2, 8000))
    
    0 讨论(0)
提交回复
热议问题