简体   繁体   中英

Query in Oracle-SQL

A table contains a column with numeric values till now. Now I want to enter details in the column with alphabets. How is it possible without losing the old data?

EX:

A student table is created and values are inserted

Here SFEE is given numeric datatype:

SNO SNAME SCOURSE SFEE
1    RAM   SQL     2100
2    JAM    JAVA   3000

SNO SNAME SCOURSE SFEE
1    RAM   SQL     2100
2    JAM    JAVA   3000
3    TOM    LINUX  AJAY

SELECT * FROM STUDENT;

SNO SNAME SCOURSE SFEE
1    RAM   SQL     2100
2    JAM    JAVA   3000
3    TOM    LINUX  AJAY

You can change the datatype if the column is empty:

ALTER TABLE student MODIFY (sfee VARCHAR2(10));

If you need to keep the data, as you said, you can rename the column, add a new column with the new datatype, copy the data over and drop the renamed old column:

CREATE TABLE student (sno NUMBER, sname VARCHAR2(10), scourse VARCHAR2(10), sfee NUMBER);
INSERT INTO student VALUES (1, 'RAM', 'SQL', 2100);
INSERT INTO student VALUES (2, 'JAM', 'JAVA', 3000);

ALTER TABLE student RENAME COLUMN sfee TO sfee_old;
ALTER TABLE student ADD (sfee VARCHAR2(10));
UPDATE student SET sfee = TO_CHAR(sfee_old,'fm9999');
ALTER TABLE student DROP COLUMN sfee_old;

If it's a large table, I'd recommend to rebuild it physically:

ALTER TABLE student MOVE;

Now SFEE can store string values:

INSERT INTO student VALUES (3, 'TOM', 'LINUX', 'AJAY');
SELECT * FROM student;

If it's a huge production table, I'd recommend to simply create a new table:

CREATE TABLE student_tmp AS 
SELECT sno, sname, scourse, to_char(sfee,'fm9999') as sfee FROM student;
DROP TABLE student;
RENAME student_tmp TO student;

Last question: Why is the SQL course cheaper then the Java course ;-) ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM