Cargando

trigger




14 Respuestas de expertos
Pulsa corazón para recibir avisos de nuevas Respuestas

  AUTOR PREGUNTA

Publicado 24 junio 2014 - 23:06
[color=#5A5A5A][font=helvetica, arial, sans-serif][size=3]que tal he estado buscando un trigger o sintaxis que debo de usar para las salidas de inventario, el chiste es que quiero que al momento de registrar una salida por ejemplo tengo 100 hojas de maquina registro que salieron 101 entonces que alli maneje un tipo de error " error solo tienes 100 en existencia " si me explico?[/size][/font][/color]

[color=#5A5A5A][font=helvetica, arial, sans-serif][size=3]Esta es mi base de datos :[/size][/font][/color]

CREATE SCHEMA IF NOT EXISTS `proyecto_v.1` DEFAULT CHARACTER SET latin1 ;
USE `proyecto_v.1` ;

-- -----------------------------------------------------
-- Table `proyecto_v.1`.`inventario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `proyecto_v.1`.`inventario` (
`id` INT NOT NULL AUTO_INCREMENT,
`insumo` VARCHAR(45) NULL,
`descripcion` VARCHAR(145) NULL,
`cantidad` INT NULL,
`precio` DOUBLE NULL,
`fecha` DATE NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `proyecto_v.1`.`usuarios`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `proyecto_v.1`.`usuarios` (
`id` INT NOT NULL AUTO_INCREMENT,
`nombre` VARCHAR(145) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `proyecto_v.1`.`salidas`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `proyecto_v.1`.`salidas` (
`id_prod` INT NOT NULL,
`id_usu` INT NOT NULL,
`cantidad` INT NULL,
`fecha` DATE NULL,
PRIMARY KEY (`id_prod`, `id_usu`),
INDEX `fk_inventario_has_Usuarios_Usuarios1_idx` (`id_usu` ASC),
INDEX `fk_inventario_has_Usuarios_inventario_idx` (`id_prod` ASC),
CONSTRAINT `fk_inventario_has_Usuarios_inventario`
FOREIGN KEY (`id_prod`)
REFERENCES `proyecto_v.1`.`inventario` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_inventario_has_Usuarios_Usuarios1`
FOREIGN KEY (`id_usu`)
REFERENCES `proyecto_v.1`.`usuarios` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `proyecto_v.1`.`mobiliario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `proyecto_v.1`.`mobiliario` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`modelo` VARCHAR(45) NOT NULL,
`marca` VARCHAR(45) NOT NULL,
`asignada_a` VARCHAR(45) NOT NULL,
`estado` VARCHAR(45) NOT NULL,
`fecha` DATE NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARACTER SET = latin1;

USE `proyecto_v.1` ;

-- -----------------------------------------------------
-- Placeholder table for view `proyecto_v.1`.`vw_salidas`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `proyecto_v.1`.`vw_salidas` (`id` INT, `insumo` INT, `cantidad` INT, `fecha` INT);

-- -----------------------------------------------------
-- View `proyecto_v.1`.`vw_salidas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `proyecto_v.1`.`vw_salidas`;
USE `proyecto_v.1`;
CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `proyecto_v.1`.`vw_salidas` AS select `proyecto_v.1`.`inventario`.`id` AS `id`,`proyecto_v.1`.`inventario`.`insumo` AS `insumo`,`proyecto_v.1`.`salidas`.`cantidad` AS `cantidad`,`proyecto_v.1`.`salidas`.`fecha` AS `fecha` from (`proyecto_v.1`.`inventario` join `proyecto_v.1`.`salidas` on((`proyecto_v.1`.`inventario`.`id` = `proyecto_v.1`.`salidas`.`id_prod`)));

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
USE `proyecto_v.1`;

DELIMITER $$
USE `proyecto_v.1`$$
CREATE
DEFINER=`root`@`localhost`
TRIGGER `proyecto_v.1`.`addEntrada`
AFTER INSERT ON `proyecto_v.1`.`salidas`
FOR EACH ROW
BEGIN

DECLARE inv_a integer;
update inventario set cantidad = cantidad - new.cantidad where id = new.id_prod;

END$$


DELIMITER ;

Adjuntos:


  • ¿Tienes la misma pregunta? Yo también
  • Volver arriba

 

Publicado 24 junio 2014 - 23:55
Te lo voy a intentar ver, avisa tu si lo consigues.

 

Publicado 25 junio 2014 - 05:39
Qué motor de bases de datos estás utilizando? MySQL, Postgre? Allí dependerá en parte la sintaxis del Trigger

 

Publicado 25 junio 2014 - 05:43
Te dejo la sintaxis para MySQL:
CREATE TRIGGER nombre_disp momento_disp evento_disp
ON nombre_tabla FOR EACH ROW sentencia_disp


   AUTOR PREGUNTA

Publicado 25 junio 2014 - 16:21
es en mysql, tenia un trigger masomenos asi pero salen algunos errores,

DECLARE inv_a int;

SELECT cantidad INTO inv_a FROM inventario WHERE id = new.id_prod;


IF inv_a >= new.cantidad THEN

update inventario set cantidad = cantidad - new.cantidad where id = new.id_prod
COMMIT;
ELSE
ROLLBACK;
END IF

busque en internet y sale que en los triggers no se utiliza el commit y el rollback pero se los dejo para que se den una mejor idea de lo quiero hacer, y gracias!! por haber contestado

   AUTOR PREGUNTA

Publicado 25 junio 2014 - 16:23
o si es de otra forma al igual pueden darme ideas

 

Publicado 25 junio 2014 - 20:22
En base a tu código te voy a dejar un ejemplo, puedes verificar la sintaxis de igual manera en la página de referencia de

Por favor Identificate o Registrate para poder ver este contenido

:

create trigger trigger_prueba before insert on inventario
for each row
begin
DECLARE x INT;
DECLARE inv_a int;
SET x = (SELECT cantidad INTO inv_a FROM inventario WHERE id = new.id_prod;);
declare mensaje varchar(255);
    if new.inv_ant >= new.x then
        set mensaje= concat('Error: No hay disponibilidad: ');
        signal sqlstate '45000' set message_text = mensaje;
    end if;
end

Me avisas cualquier cosa. Saludos.

   AUTOR PREGUNTA

Publicado 25 junio 2014 - 22:53

En base a tu código te voy a dejar un ejemplo, puedes verificar la sintaxis de igual manera en la página de referencia de

Por favor Identificate o Registrate para poder ver este contenido

:

create trigger trigger_prueba before insert on inventario
for each row
begin
DECLARE x INT;
DECLARE inv_a int;
SET x = (SELECT cantidad INTO inv_a FROM inventario WHERE id = new.id_prod;);
declare mensaje varchar(255);
if new.inv_ant >= new.x then
set mensaje= concat('Error: No hay disponibilidad: ');
signal sqlstate '45000' set message_text = mensaje;
end if;
end

Me avisas cualquier cosa. Saludos.






"me esta saliendo ese error" pero no se porque

Adjuntos:



 

Publicado 27 junio 2014 - 17:18
Prueba ahora:

create trigger trigger_prueba before insert on inventario
for each row
begin
DECLARE x INT
DECLARE inv_a int
SET x = (SELECT cantidad INTO inv_a FROM inventario WHERE id = new.id_prod)
declare mensaje varchar(255)
if new.inv_ant >= new.x then
set mensaje= concat('Error: No hay disponibilidad ')
signal sqlstate '45000' set message_text = mensaje
end if
end


   AUTOR PREGUNTA

Publicado 01 julio 2014 - 21:36
no jaja no se deja!! entonces empece a hacer otra forma corta y facil pero estoy batallando con el where cuando pongo dos codiciones : mira tengo esto

("UPDATE inventario SET cantidad='"+txt_can.getText()+"'-'"+txt_salida.getText()
+"' WHERE id='"+tbl_salidas.getValueAt(fila, 0)+ "'and cantidad >'"+txt_salida.getText());

Y me sale esto:


e: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''4' at line 1
BUILD SUCCESSFUL (total time: 20 seconds)

donde ese '4' es la cantidad que pongo de salida en un jtextfield que tengo en el jframe


X