Removing repeated duplicated characters

后端 未结 6 1426
醉酒成梦
醉酒成梦 2021-02-08 12:12

I have a string in my stored proc like \',,,sam,,bob,\' or \',,,\' from the above string I have to delete multiple commas from it, it must look like <

6条回答
  •  佛祖请我去吃肉
    2021-02-08 13:01

    This works for strings that are exclusively commas or have up to 398 contiguous commas.

     SELECT 
         CASE 
             WHEN TargetString NOT LIKE '%[^,]%' 
                 THEN '' /*The string is exclusively commas*/
             ELSE 
                REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TargetString,
                REPLICATE(',',16),','), /*399/16 = 24 remainder 15*/
                REPLICATE(',',8),','),  /* 39/ 8 =  4 remainder 7*/
                REPLICATE(',',4),','),  /* 11/ 4 =  2 remainder 3*/
                REPLICATE(',',2),','),  /*  5/ 2 =  2 remainder 1*/
                REPLICATE(',',2),',')   /*  3/ 2 =  1 remainder 1*/
             END
     FROM T    
    

    Add extra powers of 2 at the top if you need more or remove from the top if you need less. The comments by each stage indicate the smallest number that this stage will not deal with successfully.

    All the comment lines are in this format

    /*  L/D    =  Q remainder R */
    
    D:    Corresponds to the length of the string generated by `REPLICATE`
    R:    Is always D-1
    Q+R:  Form L for the next step
    

    So to extend the series upwards with another REPLICATE(',',32),',') stage

    D = 32 
    R = 31
    Q = 368 (399-31)
    L = (368 * 32) + 31 = 11807
    

    So that would deal with sections of commas up to 11,806 characters.

提交回复
热议问题