1

introducir la descripción de la imagen aquíLlevo un rato buscado una solución, y/o yo estoy muy ciego o no encuentro mi caso especifico. Espero que me puedan echar una mano...

Tengo la siguiente tabla llamada precios_producto, la cual tiene los siguientes campos

  1. IDPRECIO
  2. IDPRODUCTO (FK de la tabla producto)
  3. PRECIO_PRODUCTO
  4. FECHA_INICIO
  5. FECHA_FIN (PERMITE NULL)
  6. BORRADO (1 O 2)

El tema es que estoy intentando crear un trigger, que me permita a la hora de añadir un nuevo precio a la tabla, haga el update de la fecha fin y cambie el campo borrado a 2 del anterior registro que tenga el mismo IdProducto. Ejemplo: IMAGEN DE TABLA
En este caso se ha añadido un nuevo registro y en el antiguo quiero updatear la fecha y el borrado.
He intentado lo siguiente pero no funciona

CREATE TRIGGER Update_Precio
BEFORE INSERT ON Precio_Producto
FOR EACH ROW
DECLARE
BEGIN
UPDATE Precio_Producto SET FECHAFIN = CURRENT_DATE, BORRADO = 2 where IDProducto = NEW.IDProducto AND FECHAFIN is null and FECHAINICIO < NEW.FECHAINICIO;
END;

¿Alguien sabe algo al respecto?
EDIT: Cierto el error es el siguiente (Existe un error en su sintaxis SQL; revise el manual que se corresponde con su versión del servidor MariaDB para averiguar la sintaxis correcta a utilizar cerca de 'DECLARE BEGIN UPDATE Precio_Producto SET FECHAFIN = CURRENT_DATE, BORRADO = 2...' en la línea 4)

3
  • No se porque no me funciona la tabla....
    – Barlus00
    el 1 jul. a las 14:18
  • 1
    Según mi bola mágica (porque no mencionaste qué error da) es el error 1442 (Can't update table XXXXXXX in stored function/trigger because it is already used by statement which invoked this stored function/trigger), ¿es así? Pulsa en editar para agregar más detalles a tu pregunta.
    – padaleiana
    el 1 jul. a las 14:50
  • no es poque usas ; como separador? seeee seguro es eso...
    – gbianchi
    el 1 jul. a las 15:40

1 respuesta 1

1

En el disparador que defines tienes un par de errores: el DECLARE en el que no declaras ninguna variable y los nombres de los campos mal escritos. Para que el servidor te lo admita, deberías escribirlo así:

CREATE TRIGGER Update_Precio
  AFTER INSERT ON Precio_Producto
  FOR EACH ROW
  BEGIN
    UPDATE Precio_Producto
      SET FECHA_FIN = CURRENT_DATE, BORRADO = 2 
      WHERE IDPRODUCTO = NEW.IDPRODUCTO
      AND FECHA_FIN is NULL 
      AND FECHA_INICIO < NEW.FECHA_INICIO;
  END;

Aún sin errores, tampoco te funcionará porque no puedes hacer modificaciones en la tabla que dispara un trigger. Es una protección del servidor de bases de datos para evitar disparos infinitos, que te advertirá con este mensaje de error:

Can't update table 'Precio_Producto' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

En su lugar, lo que puedes hacer es ejecutar esta consulta inmediatamente después de hacer cada INSERT:

UPDATE Precio_Producto LEFT JOIN (
    SELECT IDPRECIO,IDPRODUCTO,FECHA_INICIO fecha
      FROM Precio_Producto JOIN (
        SELECT IDPRODUCTO,
          MAX(FECHA_INICIO) FECHA_INICIO
          FROM Precio_Producto
          GROUP BY 1  
      ) c1 USING(IDPRODUCTO,FECHA_INICIO)
  ) c2 USING(IDPRODUCTO)
  SET FECHA_FIN = fecha, BORRADO = 2
  WHERE c2.IDPRECIO!=Precio_Producto.IDPRECIO
  AND FECHA_FIN IS NULL
  AND FECHA_INICIO<fecha;

Tendrá el mismo efecto que el disparador que intentas definir, pero para todos los antiguos precios que te hayan quedado sin actualizar. Si todo está al día, simplemente no hará nada, así que realmente la puedes ejecutar cuando quieras para conseguir este resultado:

+----------+------------+-----------------+--------------+------------+---------+
| IDPRECIO | IDPRODUCTO | PRECIO_PRODUCTO | FECHA_INICIO | FECHA_FIN  | BORRADO |
+----------+------------+-----------------+--------------+------------+---------+
|        2 |          1 |              10 | 2023-07-01   | NULL       |    NULL |
|        1 |          1 |               8 | 2023-06-29   | 2023-07-01 |       2 |
+----------+------------+-----------------+--------------+------------+---------+

Aporto tu dataset por si alguien tuviera interés en reproducir el problema:

CREATE TABLE Precio_Producto(
  IDPRECIO int AUTO_INCREMENT PRIMARY KEY,
  IDPRODUCTO int,
  PRECIO_PRODUCTO float,
  FECHA_INICIO date,
  FECHA_FIN date,
  BORRADO int
  );
INSERT INTO Precio_Producto VALUES
  (1,1,8, '2023-06-29',NULL,NULL),
  (2,1,10,'2023-07-01',NULL,NULL);

Espero que te resulte útil. Si te surge cualquier duda, déjamela en los comentarios.

1
  • 1
    Muchas gracias! Me ha estallado la cabeza :D
    – Barlus00
    el 2 jul. a las 14:52

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.