• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Use SQL To Change A Substring

    February 9, 2016 Ted Holt

    Occasionally I need to change part of a string value in a database table. SQL has three mechanisms that let me accomplish such a thing. Do you know what those three mechanisms are and how to use them?

    First, we need a table for illustrative purposes.

    create table Parts
      ( ID            char(6)       primary key,
        Description   varchar(40),
        Cost          dec (5,2),
        Price         dec (5,2));
    
    insert into parts values                         
    ('XX-101', '20-inch Doodad',            0.12,    0.25),
    ('XX-105', '2-foot Doodad left-hand',   0.48,    0.75),
    ('XX-106', '2-foot Doodad right-hand',  0.48,    0.75),
    ('XX-118', '12-foot Doodad',            1.25,    3.00),
    ('BA-101', '5CM  Widget',               0.30,    0.45),
    ('BA-104', '15Cm Widget',               1.00,    1.35),
    ('BA-111', '150cm Widget',              5.00,    8.00),
    ('BA-145', 'Used 15cm Widget',          0.20,    0.80),
    ('CT-201', 'ACME chain stretcher',      4.75,   19.99),
    ('CT-202', 'Refurbished ACME sky hook', 3.00,   12.00);
    

    Mechanism 1: Substring and Concatenation

    You can use the substring function and concatenation to build a new value for a string. This method is appropriate when you know where the substring begins.

    For example, some of the parts have IDs that begin with “XX”. Let’s change “XX” to “AA”.

    update parts                        
       set ID = 'AA' concat substr(ID,3)
     where ID between 'XX' and 'XX9'    
    

    I concatenated the string “AA” to the third and following characters of the ID and assigned the result back to the ID column.

    Now the table looks like this:

    ID

    DESCRIPTION

    AA-101

    20-inch
    Doodad

    AA-105

    2-foot
    Doodad left-hand

    AA-106

    2-foot
    Doodad right-hand

    AA-118

    12-foot
    Doodad

    BA-101

    5CM Widget

    BA-104

    15Cm Widget

    BA-111

    150cm Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The string that is to be replaced and the replacement string do not have to be the same length. That happened to be the case in this example.

    Mechanism 2: The REPLACE Function

    When you don’t know where a substring will begin, you can use the REPLACE function to replace one string with another. Let’s replace the barbaric term “doodad” with the more elegant and urbane term “doohickey”.

    update parts 
       set Description = replace(Description, 'Doodad', 'Doohickey')
     where ID between 'AA' and 'AA9'
    

    Look at the descriptions now.

    ID

    Description

    AA-101

    20-inch
    Doohickey

    AA-105

    2-foot
    Doohickey left-hand

    AA-106

    2-foot
    Doohickey right-hand

    AA-118

    12-foot
    Doohickey

    BA-101

    5CM Widget

    BA-104

    15Cm
    Widget

    BA-111

    150cm
    Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The WHERE clause was not necessary, but including it prevented SQL from updating other rows unnecessarily.

    Mechanism 3: Regular Expressions

    Regular expressions are a cryptic but powerful type of wild card processing. To learn more about them, read Michael Sansoterra’s superb explanation.

    Let’s change the parts that are measured in centimeters in two ways. First, let’s make sure that the abbreviation for centimeter, cm, is in lowercase letters. Second, let’s leave only one space between cm and the following text. Here’s the update:

    update parts as p                                              
       set p.description = regexp_replace(p.description,           
                                    '([0-9]+)[Cc][Mm]( +)','$1cm ')
     where regexp_like (p.description,'[0-9]+[Cc][Mm]')            
    

    Look at the table now:

    ID

    Description

    AA-101

    20-inch
    Doohickey

    AA-105

    2-foot
    Doohickey left-hand

    AA-106

    2-foot
    Doohickey right-hand

    AA-118

    12-foot
    Doohickey

    BA-101

    5cm
    Widget

    BA-104

    15cm
    Widget

    BA-111

    150cm
    Widget

    BA-145

    Used 15cm
    Widget

    CT-201

    ACME chain
    stretcher

    CT-202

    Refurbished
    ACME sky hook

    The WHERE clause uses the regular expression like function to select the rows that have a number immediately followed by the letters “CM” in any case. Look more closely.

    where regexp_like (p.description,'[0-9]+[Cc][Mm]')
    
    • [0-9] matches any digit.
    • + means to match one or more occurrences of the preceding match. This prevents the system from selecting the ACME parts for update.
    • [Cc] tells the system to match on the letter C regardless of case.
    • [Mm] tells the system to match on the letter M regardless of case.

    The regular expression replace function changes part of the string.

    regexp_replace(p.description, '([0-9]+)[Cc][Mm]( +)','$1cm ') 
    
    • ( indicates the beginning of the first capturing group.
    • [0-9] matches any digit.
    • + means to match one or more occurrences of the preceding match.
    • ) indicates the end of the first capturing group.
    • [Cc] tells the system to match on the letter C regardless of case.
    • [Mm] tells the system to match on the letter M regardless of case.
    • ( indicates the beginning of the second capturing group.
    • The blank tells the system to look for a blank character.
    • + means to match one or more occurrences of the preceding match.
    • ) indicates the end of the second capturing group.

    When such a match is found, the system uses the third parameter to replace the matched text.

    • $1 means to include the contents of the first capturing group, which consists of the digits preceding the letters CM.
    • The letters “cm” and one blank are to be placed into the string following the first capturing group.
    • The second capturing group, which contains the blanks following “CM”, is not referenced, so the system does not include it in the replacement string.

    The remainder of the description is not part of the match, and is therefore not affected.

    So there you have it. Three replacement mechanisms. If you need to replace part of a string, you can handle it.

    RELATED STORY

    Native Regular Expressions In DB2 For i 7.1 And 7.2

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    Raz-Lee Security

    iSecurity Multi Factor Authentication (MFA) helps organizations meet compliance standards and improve the existing security environment on IBM i. It requires a user to verify his identity with two or more credentials.

    Key Features:

    • iSecurity provides Multi Factor Authentication as part of the user’s initial program
    • Works with every Authenticator App available in the Market.

    Contact us at https://www.razlee.com/isecurity-multi-factor-authentication/

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    COMMON:  2016 Annual Meeting & Expo, May 15 - 18, in New Orleans! Great Power Systems event!
    System i Developer:  RPG & DB2 Summit - March 22-24 in Dallas. Register by Feb 12 and save $300!
    BCD:  IBM i eBook: Top 10 Reasons to Choose PHP. Download now »

    IBM Patches OpenSSH Security Flaws That Impact IBM i IBM Wheels And Deals On Big Iron Compute And Memory

    Leave a Reply Cancel reply

Volume 16, Number 03 -- February 9, 2016
THIS ISSUE SPONSORED BY:

Bug Busters Software Engineering
ProData Computer Services
WorksRight Software

Table of Contents

  • IBM i and .Net Connectivity With XMLSERVICE
  • Use SQL To Change A Substring
  • Parsing Delimited Text Data Natively In SQL, Part 2: Java To The Rescue

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • IBM Tweaks Some Power Systems Prices Down, Others Up
  • Disaster Recovery: From OS/400 V5R3 To IBM i 7.4 In 36 Hours
  • The Disconnect In Modernization Planning And Execution
  • Superior Support: One Of The Reasons You Pay The Power Systems Premium
  • IBM i PTF Guide, Volume 25, Number 13
  • IBM i Has a Future ‘If Kept Up To Date,’ IDC Says
  • When You Need Us, We Are Ready To Do Grunt Work
  • Generative AI: Coming to an ERP Near You
  • Four Hundred Monitor, March 22
  • IBM i PTF Guide, Volume 25, Number 12

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2023 IT Jungle