Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2 need help for alter table alter column set data type

Tags:

sql

db2

I need to change the data type of column from VARCHAR to DECIMAL

I have data in the column, but they are all numeric values like 10.00, 25.50 etc,

Now when I do alter table MY_TABLE alter column COL1 set data type to decimal(11,2) its failing.

Whats the process i can follow here.

I'm sure this is not a new question but i couldn't find the solution, so instead of raking my brains i'm asking out here.

like image 636
Manoj Avatar asked Oct 26 '11 15:10

Manoj


People also ask

Can ALTER TABLE change data type?

We can use ALTER TABLE ALTER COLUMN statement to change the datatype of the column. The syntax to change the datatype of the column is the following. In the syntax, Tbl_name: Specify the table name that contains the column that you want to change.

Which option of alter command helps us change data type of a column?

ALTER TABLE table_name ALTER COLUMN column_name TYPE data_type; Alters the table by changing the datatype of column.

How do you modify data type?

Select the field (the column) that you want to change. On the Fields tab, in the Properties group, click the arrow in the drop-down list next to Data Type, and then select a data type. Save your changes.


1 Answers

The syntax is ALTER TABLE {tableName} MODIFY {Column-Name} {New-Column-Definition} I.E. ALTER TABLE MY_TABLE MODIFY COL1 DECIMAL(11,2)

Generally this (altering the column data type) won't convert the existing data to the new type and will probably set the incompatible values as NULL (or it may make a smart conversion it's pretty much DBMS server specific)

You can do something like this if the data volume is not too high

ALTER TABLE MY_TABLE ADD COLUMN Temporary decimal(11,2);
UPDATE MY_TABLE SET Temporary=CAST(COL1 AS DECIMAL(11,2));
ALTER TABLE MY_TABLE DROP COLUMN COL1;
ALTER TABLE MY_TABLE  CHANGE Temporary COL1 decimal(11,2);

Edit: The first part is probably incorrect

like image 172
apokryfos Avatar answered Sep 28 '22 06:09

apokryfos