How to replace every other instance of a particular character in a MySQL string?

前端 未结 5 1196
梦毁少年i
梦毁少年i 2021-01-07 22:49

How to replace value in mysql column by query like, Column is options and its of type varchar(255)

From

id   options
1    A         


        
5条回答
  •  清酒与你
    2021-01-07 23:22

    You can do by creating a function

    CREATE FUNCTION doiterate(str TEXT, i INT, next INT, isp TINYINT(1))
      RETURNS TEXT
      BEGIN
        myloop: LOOP
          IF next = 0 THEN
            LEAVE myloop;
          END IF;
          IF isp = TRUE THEN
            set str = insert(str, i, 1, ',');
            set isp = FALSE;
            set i = next;
            set next = locate('|', str, i + 1);
            ITERATE myloop;
          ELSE
            set isp = TRUE;
            set i = next;
            set next = locate('|', str, i + 1);
            ITERATE myloop;
          END IF;
          LEAVE myloop;
        END LOOP;
        return str;
      END;
    

    and calling it that way :

    SELECT t.`column`,
      @loc := locate('|', t.`column`) as position,
      @next := locate('|', t.`column`, @loc +1) as next,
      @isp := 0 is_pipe,
      @r := doiterate(t.column, @loc, @next, @isp) as returnstring
    from test t;
    

    I assume you'll be smart enough to

    • change the tablename & column name
    • insert this into an update request

    You can change the @isp := to 1 if I got the wrong pipe/coma change (i assumed second pipe should be changed to a coma)

提交回复
热议问题