How can I switch case for each letter in a string with SQL?

前端 未结 4 533
旧时难觅i
旧时难觅i 2021-01-29 11:27

I need to convert this into this using PostgreSQL

dxItw9a4 --> DXiTW9A4

Is there any function or way that is already set?

4条回答
  •  旧时难觅i
    2021-01-29 11:47

    If you're only dealing with the characters A-Z, you can use the translate function in postgres to convert cases.

    select TRANSLATE(
        'dxItw9a4', -- original text
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', -characters to change
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' -- replacement characters.
    )
    

    You can simplify it slightly be using the upper/lower functions.

    select TRANSLATE(
        'dxItw9a4',  -- original text
        upper('dxItw9a4')||lower('dxItw9a4'), --characters to search for
        lower('dxItw9a4')||upper('dxItw9a4') -- replacement characters
    );
    
    

提交回复
热议问题