3

I have a column in my database, its type is int. Now I need to store decimal numbers. How can I change its type to decimal with hook_update_N?

4

In basic terms you just need to call db_change_field() in your update function, with the spec for the new field:

function MYMOUDLE_update_7001(&$sandbox) {
  // Create the definition for the field
  $new_field = array(
    'type' => 'decimal',
    'precision' => 16,
    'scale' => 2,
    'not null' => TRUE,
    // etc...
  );

  db_change_field('table_name', 'field_name', 'field_name', $new_field);
}

If your field is a primary key/part of an index, you'll need to manually drop those indicies and recreate them (see the documentation page for a more detailed explanation).

| improve this answer | |
  • 2
    Also make sure that your previous type can be converted to the new one. This is usually less a problem with MySQL but PostgreSQL is way more strict there. – Berdir Jun 2 '12 at 8:02
  • 1
    Shouldn't the type be numeric instead of decimal? – Randell Dec 9 '13 at 15:30
  • I want to change type from varchar to int. I have changed code as 'type' => 'int', 'size' => '255', 'not null' => TRUE, but its not changing the type in db. – Rajender Rajan Aug 2 '16 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.