简体   繁体   中英

Change the values in a column from PascalCase to snake_case using SQL

I have a table in snowflake that looks like this:

 --------------------
|      fieldname     |
 --------------------
|thisIsTestOne       |
|thisIsTestTwo       |
|this_test           |
 --------------------

I need to convert the PascalCase values in the column to snake_case. Note: I only want to convert them to snake_case if they are PascalCase. The output should look like this;

 -------------------- ---------------------
|      fieldname     |    newfieldname     |
 -------------------- ---------------------
|thisIsTestOne       |this_is_test_one     |
|thisIsTestTwo       |this_is_test_two     |
|this_test           |this_test            |
 -------------------- ---------------------

You should be able to use REGEXP_REPLACE to insert an underscore between a lower-case character followed by an upper-case character, and then LOWER to convert to lower case ie

SELECT LOWER(REGEXP_REPLACE(fieldname, '([a-z])([A-Z])', '\\1_\\2'))
FROM yourtable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM