0

I have a problem to making a trigger. I want make a 'copy' of field 'nome' in 'nome1' whenever I make an insert of a record (casello). I receive this error:

#1442 - Can't update table 'casello' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

How Can i fix it? this is the structure of my table:

    --
    -- Struttura della tabella `casello`
    --

   CREATE TABLE IF NOT EXISTS `casello` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `posizione` double NOT NULL,
  `nome` varchar(100) NOT NULL,
  `nome1` varchar(100) DEFAULT NULL,
  `modalita_pagamento` varchar(255) NOT NULL,
  `servizio_assistenza` tinyint(1) DEFAULT NULL,
  `l_nome` varchar(100) DEFAULT NULL,
  `nome_autostrada` varchar(4) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `l_nome` (`l_nome`),
  KEY `nome_autostrada` (`nome_autostrada`),
  KEY `nome` (`nome`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;

  --
  -- Dump dei dati per la tabella `casello`
  --

  INSERT INTO `casello` (`id`, `posizione`, `nome`, `nome1`, `modalita_pagamento`,
          `servizio_assistenza`, `l_nome`, `nome_autostrada`) VALUES
  (3, 35, 'napoli nord', NULL, 'contanti, carte, telepass', 1, 'caserta', 'a1'),
  (4, 15, 'napoli sud', NULL, 'contanti, carte, telepass', 1, 'napoli', 'a1'),
  (5, 310, 'roma nord', NULL, 'contanti, carte, telepass', 1, NULL, 'a1'),
  (6, 280, 'roma sud', NULL, 'contanti, carte, telepass', 1, NULL, 'a1'),
  (11, 25, 'palma campania', 'NULL', 'contanti, carte, telepass', 1, NULL, 'a30'),
  (12, 30, 'sarno', 'NULL', 'contanti, carte, telepass', NULL, NULL, 'a30'),
  (13, 35, 'nocera', NULL, 'contanti, carte, telepass', 1, NULL, 'a30');

  --
  -- Triggers `casello`
  --
  DROP TRIGGER IF EXISTS `cp nome nome1`;
  DELIMITER //
  CREATE TRIGGER `cp nome nome1` AFTER INSERT ON `casello`
  FOR EACH ROW UPDATE casello
  set casello.nome1=casello.nome
  //
  DELIMITER ;

P.S. Of course if I make this:

UPDATE casello
SET casello.nome1=casello.nome

as a simple query it will works and it copies data.

1 Answers1

0

You can achieve it like this:

DROP TRIGGER IF EXISTS `cp nome nome1`;
DELIMITER //
CREATE TRIGGER `cp nome nome1` BEFORE INSERT ON `casello`
FOR EACH ROW 
SET NEW.nome1=NEW.nome
//
DELIMITER ;

You don't make an UPDATE after the rows are inserted, you change them BEFORE they are INSERTed.

Note, NEW is a keyword here, not a table name.

fancyPants
  • 50,732
  • 33
  • 89
  • 96