SQL method to replace repeating blanks with single blanks

前端 未结 15 1934
既然无缘
既然无缘 2020-12-01 17:52

Is there a more elegant way of doing this. I want to replace repeating blanks with single blanks....

   declare @i int

    set @i=0
    while @i <= 20
           


        
相关标签:
15条回答
  • 2020-12-01 18:50

    For me the above examples almost did a trick but I needed something that was more stable and independent of the table or column or a set number of iterations. So this is my modification from most of the above queries.

    CREATE FUNCTION udfReplaceAll 
    (
        @OriginalText NVARCHAR(MAX),
        @OldText NVARCHAR(MAX),
        @NewText NVARCHAR(MAX)
    )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN
        WHILE (@OriginalText LIKE '%' + @OldText + '%')
        BEGIN
            SET @OriginalText = REPLACE(@OriginalText,@OldText,@NewText)
        END
    
        RETURN @OriginalText
    END
    GO
    
    0 讨论(0)
  • 2020-12-01 18:52
    SELECT 'starting...' --sets @@rowcount
    WHILE @@rowcount <> 0
        update myTable
        set myTextColumn = replace(myTextColumn, '  ', ' ')
        where myTextColumn like '%  %'
    
    0 讨论(0)
  • 2020-12-01 18:52
    REPLACE(REPLACE(REPLACE(myTextColumn,' ',' %'),'% ',''),'%','')
    

    Statement above worked terrifically for replacing multiple spaces with a single space. Optionally add LTRIM and RTRIM to remove spaces at the beginning.

    Got it from here: http://burnignorance.com/database-tips-and-tricks/remove-multiple-spaces-from-a-string-using-sql-server/

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