1
Name            Nameid
P,q,r,s,t       One
A,b,c           Two
D,e             Three

This is my source table, but i want my target table like this

Name    Nameid
P       One
Q       One
R       One
S       One
T       One
A       Two
B       Two
C       Two
D       three
alf
  • 18,372
  • 10
  • 61
  • 92
  • 2
    spit columns? sometimes I wish I could spit columns. – Taryn Mar 02 '12 at 12:40
  • possible duplicate of [Split column to multiple rows](http://stackoverflow.com/questions/3713107/split-column-to-multiple-rows) – APC Mar 02 '12 at 13:25

3 Answers3

1

In a case like this, I think it would be more elegant to store the data in a different way.

If you are inserting your rows from a program, try splitting your string there, and insert a few more rows instead.

Let me give you a pseudo code example.

number = "One"
many_letters = "P,Q,R,S,T".split(",")
for(letter in many_letters) {
     insert_values(letter, number)
}
professorsloth
  • 339
  • 1
  • 10
1

Here's one way, lifted from here:

SQL> CREATE TABLE t (name VARCHAR2(20), nameid VARCHAR2(10));

Table created.

SQL> INSERT INTO t VALUES ('P,q,r,s,t','One');

1 row created.

SQL> INSERT INTO t VALUES ('A,b,c'    ,'Two');

1 row created.

SQL> INSERT INTO t VALUES ('D,e'      ,'Three');

1 row created.

SQL> SELECT     nameid
  2  ,          REGEXP_SUBSTR (name, '[^,]+', 1, LEVEL) AS token
  3  FROM       t
  4  CONNECT BY PRIOR nameid = nameid
  5  AND        REGEXP_INSTR (name, '[^,]+', 1, LEVEL) > 0
  6  AND        PRIOR DBMS_RANDOM.STRING ('p', 10) IS NOT NULL
  7  ;

NAMEID     TOKEN
---------- --------------------
One        P
One        q
One        r
One        s
One        t
Three      D
Three      e
Two        A
Two        b
Two        c

10 rows selected.

SQL>
Tebbe
  • 1,372
  • 9
  • 12
-3

Sorry I didn't understand the question it was posted. It's been reformatted since.

Oracle does not have a built in Split function, which is what you need here. The following link shows how to create a custom Split function:

http://srinisreeramoju.blogspot.com/2010/03/oracle-custom-split-function.html

Once you've created the types and the function you would simply call it as:

SELECT
    Split(Name, ',') AS Name,
    NameID
FROM
    YourTable
Tobsey
  • 3,390
  • 14
  • 24