I have a variable in Oracle that contains a string. This string has many words separated by $. I want to know if I can use Split Function to get the list of word.
Example:
Suppose that [variable] contains (hello$wordl$stack$overflow)
SELECT COLUMN_VALUE AS Description FROM TABLE( split_String( variable ) );
Description
hello
world
stack
overflow
CodePudding user response:
Yes, just define a split_string
function to do it:
CREATE OR REPLACE TYPE stringlist AS TABLE OF VARCHAR2(20)
/
CREATE OR REPLACE FUNCTION split_String(
i_str IN VARCHAR2,
i_delim IN VARCHAR2 DEFAULT ','
) RETURN stringlist DETERMINISTIC
AS
p_result stringlist := stringlist();
p_start NUMBER(5) := 1;
p_end NUMBER(5);
c_len CONSTANT NUMBER(5) := LENGTH( i_str );
c_ld CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
IF c_len > 0 THEN
p_end := INSTR( i_str, i_delim, p_start );
WHILE p_end > 0 LOOP
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
p_start := p_end c_ld;
p_end := INSTR( i_str, i_delim, p_start );
END LOOP;
IF p_start <= c_len 1 THEN
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start 1 );
END IF;
END IF;
RETURN p_result;
END;
/
Then:
SELECT COLUMN_VALUE AS Description
FROM TABLE( split_String( 'hello$world$stack$overflow', '$' ) );
If you want to use a bind variable instead of a literal then you can:
SELECT COLUMN_VALUE AS Description
FROM TABLE( split_String( :variable, '$' ) );
(or ?
for an anonymous bind variable.)
Outputs:
DESCRIPTION hello world stack overflow
db<>fiddle here
CodePudding user response:
I created a table name emp with one column name as name;
Following are the SQL i have used.
- create table emp (name varchar2(20));
- insert into emp values('Hello$WOrld$User');
SELECT LEVEL AS id, REGEXP_SUBSTR(emp.name, '[^$] ', 1, LEVEL) AS data FROM emp CONNECT BY REGEXP_SUBSTR(emp.name, '[^$] ', 1, LEVEL) IS NOT NULL;
ID | DATA |
---|---|
1 | Hello |
2 | world |
3 | User |