MySQL Use last inserted id from stored procedure - mysql

Through phpmyadmin's interface, I created a stored procedure as follows:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_checkin_create`(IN `userid` INT(10), IN `organizationid` INT(10), IN `checkindate` DATETIME(6), IN `checkoutdate` DATETIME(6), IN `checkinid` INT(10))
NO SQL
Insert Into checkin Values(CheckInID, UserID, OrganizationID, CheckInDate, CheckOutDate) ON DUPLICATE
KEY UPDATE CheckInID=CheckInID, UserID=userid, OrganizationID=organizationid, checkindate=checkindate, CheckOutDate=checkoutdate$$
DELIMITER ;
How do I return LAST_INSERT_ID() from this procedure? I know the use-case of:
SELECT LAST_INSERTED_ID();
But i can't find a way to combine this query in the procedure without getting ambiguous errors.
Any help would be appreciated.
EDIT 1
Create table statement:
DROP TABLE IF EXISTS `checkin`;
CREATE TABLE IF NOT EXISTS `checkin` (
`CheckInID` int(11) NOT NULL AUTO_INCREMENT,
`UserID` int(11) NOT NULL,
`OrganizationID` int(11) DEFAULT NULL,
`CheckInDate` datetime DEFAULT NULL,
`CheckOutDate` datetime(6) NOT NULL,
PRIMARY KEY (`CheckInID`),
UNIQUE KEY `CheckInID` (`CheckInID`)
) ENGINE=MyISAM AUTO_INCREMENT=4407 DEFAULT CHARSET=latin1;

Formally:
DELIMITER $$
CREATE
DEFINER=`root`#`localhost`
PROCEDURE `sp_checkin_create` ( IN `userid` INT(10),
IN `organizationid` INT(10),
IN `checkindate` DATETIME(6),
IN `checkoutdate` DATETIME(6),
IN `checkinid` INT(10),
OUT inserted_id BIGINT )
NO SQL
BEGIN
Insert Into checkin
Values (CheckInID, UserID, OrganizationID, CheckInDate, CheckOutDate)
ON DUPLICATE KEY UPDATE
UserID=userid, OrganizationID=organizationid, checkindate=checkindate, CheckOutDate=checkoutdate;
SELECT LAST_INSERT_ID() INTO inserted_id;
END;
$$
DELIMITER ;
and
CALL sp_checkin_create(123, 456, '2021-01-01', '2021-01-01', 789, #last_inserted_id);
SELECT #last_inserted_id;
Really: LAST_INSERT_ID() is used only when autoincrement generates new value - so it makes no sense in both cases (both new row inserted with AI explicit assigning and ODKU fired).

Related

Trigger dows not let me insert data in mysql

i am trying to get used to triggers. I created a small database and a trigger. When i go to insert something in ship category it does not let me do it.If i drop the trigger with the same commend i can insert values at the table. I get this error: #1048 - Column 'IMO' cannot be null
My trigger code is:
/*ship insert*/
DELIMITER //
CREATE TRIGGER `ship_insert_logs`
AFTER INSERT ON `ship`
FOR EACH ROW
BEGIN
DECLARE ship_IMO INTEGER;
SET ship_IMO=new.IMO;
INSERT INTO ship_logs VALUES (null, concat('A new row is inserted with IMO ', ship_IMO, 'at',
date_format(now(), '%d-%m-%y %h:%i:%s %p')));
END //
DELIMITER ;
and ship table is:
CREATE TABLE ship(
department_id INTEGER NOT NULL,
IMO BIGINT PRIMARY KEY NOT NULL,
Latitude DOUBLE PRECISION NOT NULL,
Longitude DOUBLE PRECISION NOT NULL,
current_speed DOUBLE PRECISION NOT NULL,
heading VARCHAR (30),
status VARCHAR(30),
FOREIGN KEY(department_id) REFERENCES department (department_id) ON UPDATE CASCADE
);
while ship_logs table is:
CREATE TABLE ship_logs(
IMO BIGINT PRIMARY KEY NOT NULL,
audit_description VARCHAR(500)
);

How to get a row by ID in a MySQL Stored Procedure?

I have a problem with a Stored Procedure in MySQL. I want to get a single row by passing the ID parameter, however, it seems the SP ignores the WHERE filter and displays all the columns of the table.
What I find strange is that if I pass a specific value for id in a query outside the stored procedure, for example 1003, returns the expected result.
Sorry if my mistake is silly, I'm newbie.
The table structure is something like this:
CREATE TABLE Paciente
(
ID INT AUTO_INCREMENT NOT NULL,
DNI CHAR(8) UNIQUE NULL,
Nombre NVARCHAR(70) NOT NULL,
Apellido_Paterno NVARCHAR(30) NOT NULL,
Apellido_Materno NVARCHAR(30) NOT NULL,
Edad TINYINT NOT NULL,
Sexo CHAR(1) NOT NULL,
Calle NVARCHAR(50) NULL,
Numero_Domicilio SMALLINT(4) NULL,
Telefono NVARCHAR(8) NULL,
Movil NVARCHAR(10) NULL,
Estado_Civil NVARCHAR(20) NULL,
Ocupacion NVARCHAR(30) NULL,
Fecha_Registro DATETIME DEFAULT CURRENT_TIMESTAMP,
Estado BOOLEAN NULL DEFAULT TRUE,
PRIMARY KEY(ID)
)ENGINE = InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1000;
Stored Procedure:
DELIMITER $$
CREATE PROCEDURE `buscarPaciente`(IN id INT)
BEGIN
SELECT * FROM Paciente WHERE ID = id LIMIT 1;
END
$$
DELIMITER ;
The behaviour is caused by naming the input parameter same as the column name, therefore mysql cannot distinguish between the column and the parameter within the where clause. Rename the input parameter to let's say param_ID and it will return the record with the requested ID value.
DELIMITER $$
CREATE PROCEDURE `buscarPaciente`(IN param_ID INT)
BEGIN
SELECT * FROM Paciente WHERE ID = param_ID LIMIT 1;
END
$$
DELIMITER ;
DELIMITER $$
CREATE PROCEDURE `Student`(IN param_ID INT)
BEGIN
SELECT * FROM Student WHERE **Student.ID = param_ID** LIMIT 1;
END
$$
DELIMITER ;

insert is failing because of my trigger mysql

I have a problem with my trigger code.
After I wrote my trigger I wrote Insert to test the trigger. But my Insert gets error as
Error Code:1109. Unknown table employees in field list.
If I put the insert before the trigger-everything works perfect. But I want this Insert to test the trigger.
drop database if exists kontrolno;
create database kontrolno;
use kontrolno;
CREATE TABLE departments(
id TINYINT UNSIGNED PRIMARY KEY,
name CHAR(12) NOT NULL,
min_salary SMALLINT UNSIGNED NOT NULL,
max_salary SMALLINT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE employees(
id SMALLINT UNSIGNED PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary SMALLINT UNSIGNED NOT NULL,
department_id TINYINT UNSIGNED,
constraint FOREIGN KEY (department_id)
REFERENCES departments(id)
) ENGINE=InnoDB;
insert into departments(id,name,min_salary,max_salary)
values(1,"qa", 800,2000),
(2,"jd",1200,3500);
DROP TRIGGER if exists checkSalary;
delimiter |
create trigger checkSalary before Insert on employees
for each row
begin
if(employees.salary>max_salary OR employees.salary<min_salary)
then signal sqlstate '45000' set MESSAGE_TEXT="the salary is not valide";
end if;
end;
|
delimiter ;
insert into employees(id,name,salary,department_id)
values(1,"ivan", 200,1);
You had mistakes in your trigger code.
The trigger code should be:
DROP TRIGGER if exists checkSalary;
delimiter |
create trigger checkSalary before Insert on employees
for each row
begin
if(new.salary>(select max_salary from departments where id=new.department_id)
OR
new.salary<(select min_salary from departments where id=new.department_id) )
then signal sqlstate '45000' set MESSAGE_TEXT="the salary is not valid";
end if;
end;
|
delimiter ;

Error importing a previously exported mysql trigger

I had a mysql trigger that has been working, I exported it and removed it and am trying to put it back, but I keep running into the following error:
#1064 - 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 '' at line 12
My trigger is:
CREATE TRIGGER `accounts_tracking` AFTER UPDATE ON `accounts`
FOR EACH ROW BEGIN
IF( NEW.`check_level` != OLD.`check_level` ) THEN
INSERT INTO `accounts_tracking` ( `change_type`, `account_id`, `field`, `old_int`, `new_int`, `old_time`, `new_time` )
VALUES
( "1",
OLD.id,
"check_level",
OLD.`check_level`,
NEW.`check_level`,
UNIX_TIMESTAMP(),
UNIX_TIMESTAMP());
END IF;
END
Line #12 is the 2nd UNIX_TIMESTAMP()
My table structure is as follows:
CREATE TABLE `accounts_tracking` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`change_type` smallint(5) unsigned NOT NULL,
`account_id` int(10) unsigned NOT NULL,
`field` varchar(255) NOT NULL,
`old_int` int(11) NOT NULL,
`new_int` int(11) NOT NULL,
`new_time` int(10) unsigned NOT NULL,
`old_time` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `account_id` (`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Server type: MySQL
Server version: 5.1.73-log
Thanks.
As barranka suggested in comments section, you need to enclose this trigger in a delimiter, like so:
DELIMITER $$
CREATE TRIGGER `accounts_tracking` AFTER UPDATE ON `accounts`
FOR EACH ROW BEGIN
IF( NEW.`check_level` != OLD.`check_level`) THEN
INSERT INTO `accounts_tracking` ( `change_type`, `account_id`, `field`, `old_int`, `new_int`, `old_time`, `new_time` )
VALUES
( "1",
OLD.id,
"check_level",
OLD.`check_level`,
NEW.`check_level`,
UNIX_TIMESTAMP(),
UNIX_TIMESTAMP());
END IF;
END$$
DELIMITER ;
The reason is that by adding a Begin and End to the statement you are essentially creating a stored routine/procedure with the trigger itself. In order to run multiple statements, like in stored routine/procedure, you need to add delimiters.
In other cases where you do not have the Begin and End within the trigger, you do not need the delimiters. For Example:
CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET #sum = #sum + NEW.amount;

Reserve/Assign a new row in another table with each row added in one

I'll like to find out if it's possible to do the following:
after insertion of data into table a, a row will be created automatically in table b and the Note_Id (its primary key) will be stored in one of the attributes (which is a foreign key that references to the primary key in table b) in table a.
CREATE TABLE table_a ( D_Id int(5) NOT NULL AUTO_INCREMENT,
User_Id int(8) not null,
Note_Id int(5) not null, -- this is the foreign key that points to table b
PRIMARY KEY (D_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE table_b ( Note_Id int(5) NOT NULL AUTO_INCREMENT,
Note_Description varchar(50) null,
PRIMARY KEY (Note_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thanks!
delimiter $$
CREATE TRIGGER ins_Document
AFTER INSERT ON TABLE_A FOR EACH ROW
BEGIN
set #notenum=(Select max(Note_Id) from TABLE_B);
if(#notenum=0) then begin new.Note_Id=1;
end;
else
new.Note_Id=#notenum+1;
end if;
INSERT INTO TABLE_B (Note_Id) VALUES (NEW.Note_Id);
END$$
delimiter ;
Have a look into triggers: Create Trigger
Here you can react on events like inserts into a table and define respective actions for that.