12

I have a child table. and foreign key there with ON DELETE CASCADE while creating the table.

There are no records either in child or parent table.

I want the primary key, foreign key to be as they are but want to remove only the CASCADING option from the child table .

is there anyway that i can Alter that child table.

Thank you.

Raghav
  • 195
  • 1
  • 3
  • 6

4 Answers4

5

The table:

SHOW CREATE TABLE table; 
CREATE TABLE `table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_departamento` int(11) unsigned DEFAULT NULL,
  `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id_departamento` (`id_departamento`),
  CONSTRAINT `departamentos_direcciones_pedidos_ibfk_1` FOREIGN KEY (`id_departamento`) REFERENCES `departamentos` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  1. First drop foreign key.
ALTER TABLE departamentos_direcciones_pedidos DROP CONSTRAINT departamentos_direcciones_pedidos_ibfk_1;
  1. Second, create the correct foreign key
ALTER TABLE departamentos_direcciones_pedidos ADD FOREIGN KEY (id_departamento) REFERENCES departamentos(id);
Daniel
  • 214
  • 4
  • 9
3
ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }

The default is NO ACTION.

So try altering your child table back to default.

knkarthick24
  • 3,106
  • 15
  • 21
  • fid number(5) references parent(pid) on delete cascade; so i need to issue alter table child modify fid on delete set default..... right ? – Raghav Oct 28 '14 at 10:45
1

(Oracle) You can only alter the state of a constraint. ON DELETE is not a state. So you need to drop constraint and recreate it.

drop table t1 cascade constraints;
create table t1 (id number unique, rid number constraint t1_fk references t1(id) on delete cascade);

alter table t1 drop constraint t1_fk;
alter table t1 add constraint t1_fk foreign key(rid) references t1(id);

if you're using Oracle there are different dictionary views which might help you to recreate the constraint correctly

Multisync
  • 8,657
  • 1
  • 16
  • 20
1
  • Export the database as a .sql file
  • Then press ctrl + H to replace all ON DELETE CASCADE with ""
  • Then drop the tables from the DB and use the new file to instantiate a new one without ON DELETE CASCADE
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49