使用 SQL 将列中的值从 PascalCase 更改为 snake_case

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

我有一个 table 的雪花,看起来像这样:

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

我需要将列中的 PascalCase 值转换为 snake_case。注意:如果它们是 PascalCase,我只想将它们转换为 snake_case。输出应如下所示;

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

您应该可以使用 REGEXP_REPLACE to insert an underscore between a lower-case character followed by an upper-case character, and then LOWER 转换为小写,即

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