How can I alter a column of number to a list of numbers.
In myTable, m_no is an integer. Now I wish to change m_no column to a list of integers without loosing the currently stored values.
CREATE TABLE myTable (
m_id,
m_no
);
How can I alter a column of number to a list of numbers.
In myTable, m_no is an integer. Now I wish to change m_no column to a list of integers without loosing the currently stored values.
CREATE TABLE myTable (
m_id,
m_no
);
On
That's not a straightforward task as you can't change column's datatype if that column isn't empty (and yours isn't).
Moreover, it depends on what you call a "list of integers"; a simple option is if it represents a string with comma-separated integer values. Basically, a varchar2 datatype column. Or, did you mean to use a nested table?
Presuming it is a simple string, here's a walkthrough:
Original table with some values:
SQL> create table mytable (m_id number, m_no number);
Table created.
SQL> insert into mytable values (1, 100);
1 row created.
If you just try to change m_no column's datatype, it won't work:
SQL> alter table mytable modify m_no varchar2(50);
alter table mytable modify m_no varchar2(50)
*
ERROR at line 1:
ORA-01439: column to be modified must be empty to change datatype
Therefore, add a new column (to store "original" value):
SQL> alter table mytable add m_no_old number;
Table altered.
SQL> update mytable set m_no_old = m_no;
1 row updated.
Empty the original column:
SQL> update mytable set m_no = null;
1 row updated.
Change its datatype:
SQL> alter table mytable modify m_no varchar2(50);
Table altered.
Move original values back:
SQL> update mytable set m_no = m_no_old;
1 row updated.
Drop newly added column:
SQL> alter table mytable drop column m_no_old;
Table altered.
Add some more integers into it:
SQL> update mytable set m_no = m_no || ', 200, 300';
1 row updated.
Result:
SQL> select * from mytable;
M_ID M_NO
---------- --------------------------------------------------
1 100, 200, 300
Don't try to store a list of numbers in a column (especially not as comma-separated values).
What you should do is create another table:
Then, when you want to get the list of numbers for an id you can use a
JOIN:Which, for the sample data:
Outputs:
Or, if you want a comma-separated list of numbers (for display purposes) then
JOINand aggregate:Which outputs:
If you want to modify the existing table to use two tables then:
myTable_numberstable using the DDL statement above (without the referential constraint).INSERT INTO mytable_numbers (m_id, m_no) SELECT m_id, m_no FROM my_table;m_nocolumn frommytable.m_idvalues frommyTable.mytable.m_id.mytable_numbers.m_idtomytable.m_id.If you really want a list of numbers in a column (don't) then use a nested table:
Then you can insert the same data:
And use the queries:
or
giving the same output as above.
fiddle