Domanda

I want to change underscore-separated strings:

my_underscore_separated_string

into CamelCase:

MyUnderscoreSeparatedString

With an SQL statement. What is the best way to do this conversion (in a table in Oracle)?

I can match the underscores with REGEXP_REPLACE, but there's no way to change the case of a backreference. INSTR/SUBSTR manipulation will only allow me to convert one underscore at a time.

È stato utile?

Soluzione

How to use SQL (In Oracle) to convert underscore delimited words to camel case:

  1. Replace all the underscores with spaces.

  2. Use This function against the String: INITCAP(string)

  3. Then replace all spaces with blankstring.

You should be able to do this in one line. SQL is not optimized for these sorts of string manipulation tasks so if you do a lot of these, expect it to take way too long.

Altri suggerimenti

A small PL/SQL wrapper can run the conversion repeatedly until no more underscores are found. I've included a few extra statements to match my company's camelcasing convention (initial capital and capitalized "ID").

UPDATE md_field SET NAME = lower(NAME) WHERE NAME LIKE '%\_%' ESCAPE '\';
UPDATE md_field SET NAME = upper(substr(NAME, 1, 1))||substr(NAME, 2) WHERE NAME LIKE '%\_%' ESCAPE '\';
UPDATE md_field SET NAME = REPLACE(NAME, 'id', 'ID') WHERE NAME LIKE '%\_%' ESCAPE '\';
DECLARE
vsql             LONG;
v_cnt            NUMBER;
BEGIN
  LOOP
    vsql := 'UPDATE md_field SET NAME = substr(NAME, 1, instr(NAME, ''_'')-1)||upper(substr(NAME, instr(NAME, ''_'')+1, 1))||substr(NAME, instr(NAME, ''_'')+2) WHERE NAME LIKE ''%\_%'' ESCAPE ''\''';
    EXECUTE IMMEDIATE vsql;
    SELECT COUNT (*) INTO v_cnt FROM md_field WHERE NAME LIKE '%\_%' ESCAPE '\';
    EXIT WHEN v_cnt = 0;
  END LOOP;
END;
/
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top