SQL: search/replace but only the first time a value appears in record

后端 未结 9 816
执念已碎
执念已碎 2020-12-11 02:11

I have html content in the post_content column.

I want to search and replace A with B but only the first time A appears in the record as it may appear more than onc

相关标签:
9条回答
  • 2020-12-11 03:09

    Alternatively, you could use the functions LOCATE(), INSERT() and CHAR_LENGTH() like this:

    INSERT(originalvalue, LOCATE('A', originalvalue), CHAR_LENGTH('A'), 'B')
    

    Full query:

    UPDATE wp_posts
    SET post_content = INSERT(originalvalue, LOCATE('A', originalvalue), CHAR_LENGTH('A'), 'B');
    
    0 讨论(0)
  • 2020-12-11 03:13

    If you are using an Oracle DB, you should be able to write something like :

    UPDATE wp_posts SET post_content = regexp_replace(post_content,'A','B',1,1)
    

    See here for more informations : http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions130.htm

    Note : you really should take care of post_content regarding security issue since it seems to be an user input.

    0 讨论(0)
  • 2020-12-11 03:14

    To keep the sample of gjreda a bit more simple use this:

    UPDATE wp_post
        SET post_content =
                CONCAT(
                    REPLACE(LEFT(post_content, 1), 'A', 'B'),
                    SUBSTRING(post_content, 2)
                ) 
        WHERE post_content LIKE 'A%';
    
    0 讨论(0)
提交回复
热议问题