Monday, July 14, 2014

MySQL break string into two parts





I have a field CRSE containing information "COGS 101" in table
fmcontract_course_assignment
 I want to break the field in to two parts  based on space and put them into new two fields:
 CourseSubject, CourseNumber.
1) First I create  new two fields:
ADD `CourseSubject` VARCHAR(50) NULL DEFAULT NULL , ADD `CourseNumber` VARCHAR(16) NULL DEFAULT NULL ;

2) Update these two news field from  split of filed CRSE:

UPDATE `fmcontract_course_assignment`  SET
    `CourseSubject` = IF(
        LOCATE(' ', `CRSE`) > 0,
        SUBSTRING(`CRSE`, 1, LOCATE(' ', `CRSE`) - 1),
        `CRSE`
    ),
    `CourseNumber` = IF(
        LOCATE(' ', `CRSE`) > 0,
        SUBSTRING(`CRSE`, LOCATE(' ', `CRSE`) + 1),
        NULL
    );
 Note:
  • CRSE values without a space: it will add the whole string to memberfirst and sets CourseNumber  to NULL.
  • CRSE values that have multiple spaces: it will add everything before the first space to CourseSubject  and the remainder (including additional spaces) to CourseNumber.

No comments:

Post a Comment