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

前端 未结 4 499
旧时难觅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条回答
  •  无人及你
    2021-01-29 12:00

    Here is a solution that works by splitting the string into a resultset of charaters using regexp_split_to_table(), then converts them to the opposite case and joins them again using aggregate function string_agg():

    select 
        string_agg(case when c ~ '[a-z]' then upper(c) else lower(c) end, '') res
    from (
        select * from regexp_split_to_table('dxItw9a4', '') as chars(c)
    ) x
    

    Demo on DB Fiddle:

    | res      |
    | :------- |
    | DXiTW9A4 |
    

提交回复
热议问题