Get the Unique ID for the Last Inserted Row - mysql

I want to get the Unique ID for the Last Inserted Row inside stored procedure, I make like this
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
id = mysqli_insert_id (insert into `system_users`( `username`,`password`) values (userName ,md5(password)) );
IF id <> 0 THEN
insert into `user_profile`( `full_name`,`Date_time_ added`,`added_by`) values (userName ,CURRENT_TIMESTAMP(),addedBy ) where `user_id`=id ;
END IF
END //
DELIMITER ;
This error occur
#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 '= mysqli_insert_id (insert into `system_users`( `username`,`password`) values (' at line 7
I doubt it's from mysqli_insert_id , what should I do ?

Your mysqli_insert_id is the problem, you're writing a MySQL stored procedure, not PHP. You want to use the last_insert_id() function:
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.
You also need to fix your assignment syntax. Something more like this:
DELIMITER //
CREATE PROCEDURE addNewUsers(IN userName varchar(128),IN password varchar(128), IN addedBy INT)
BEGIN
DECLARE id int default 0;
insert into `system_users`( `username`,`password`) values (userName ,md5(password));
set id = last_insert_id();
if id <> 0 then
-- ...

Related

Syntax error in MySQL procedure while using if else insert query

I am trying to create a stored procedure with MySQL but I kept receiving the error prompt but i cant find the error in my query.
I'm coming from MS SQL background and I'm not sure how is my query wrong. Anyone understands the error?
Error Code: 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 11
CREATE PROCEDURE SP_AddUpdateUser
(
IN InputUsername VARCHAR(512),
IN InputPassword VARCHAR(512),
IN InputEmail VARCHAR(512)
)
BEGIN
if(NOT EXISTS(SELECT 1 FROM TB_User WHERE Username = InputUsername)) then
INSERT INTO TB_User(Username, Password, Email, DateCreated)
SELECT InputUsername, InputPassword, InputEmail, Now();
else
UPDATE TB_User SET Password = InputPassword, Email = InputEmail WHERE Username = InputUsername;
end if;
END;;
You are taking the wrong approach in MySQL. It has a single statement that supports "upserts" -- and insert with on duplicate key update.
This is triggered when you have a unique index or constraint on the column that cannot be duplicated. In this case, username.
Start with a unique constraint or index:
create unique index unq_tb_user_username on TB_User(username);
You may already have this. Then, the body of the procedure would simply be:
CREATE PROCEDURE SP_AddUpdateUser
(
IN InputUsername VARCHAR(512),
IN InputPassword VARCHAR(512),
IN InputEmail VARCHAR(512)
)
BEGIN
INSERT INTO TB_User(Username, Password, Email, DateCreated)
SELECT InputUsername, InputPassword, InputEmail, Now()
ON DUPLICATE KEY UPDATE Password = InputPassword, Email = InputEmail;
END;
Here is a db<>fiddle.
Put ; after now(). In stored scripts you have to use semicolon after each statement.

MySQL PROCEDURE using IF Statement with #Parameter Not Working

Why is the data not being inserted on the table when I execute the procedure, what seems to be lacking with the code?
I'm testing the procedure on phpMyAdmin > myDatabase > Procedures "Routines Tab" and clicking "Execute", prompts with a modal and ask for the values of "#idproc and #nameproc.
I tried with just the INSERT code it works, but when I add the IF condition it doesn't work.
Using XAMPP 8.0.3,
10.4.18-MariaDB
DELIMITER $$
CREATE DEFINER=`root`#`localhost:3307` PROCEDURE `testproc`(IN `idproc` INT, IN `nameproc` VARCHAR(100))
BEGIN
IF #idproc = 0 THEN
INSERT INTO testproc(
id,
name)
VALUES(
#idproc,
#nameproc
);
ELSE
UPDATE testproc
SET
id = #idproc,
name = #nameproc
WHERE id = #idproc;
END IF;
SELECT * FROM testproc;
END$$
DELIMITER ;
You mix local variables (their names have not leading #) and user-defined variables (with single leading #). This is two different variable types, with different scopes and datatype rules. Procedure parameters are local variables too.
So when you use UDV which was not used previously you receive NULL as its value - and your code works incorrectly. Use LV everywhere:
CREATE DEFINER=`root`#`localhost:3307`
PROCEDURE `testproc` (IN `idproc` INT, IN `nameproc` VARCHAR(100))
BEGIN
IF idproc = 0 THEN
INSERT INTO testproc (name) VALUES (nameproc);
ELSE
UPDATE testproc SET name = nameproc WHERE id = idproc;
END IF;
SELECT * FROM testproc;
END
You do not check does specified idproc value exists in the table. If it is specified (not zero) but not exists then your UPDATE won't update anything. Assuming that id is autoincremented primary key of the table I recommend to use
CREATE DEFINER=`root`#`localhost:3307`
PROCEDURE `testproc` (IN `idproc` INT, IN `nameproc` VARCHAR(100))
BEGIN
INSERT INTO testproc (id, name)
VALUES (idproc, nameproc)
ON DUPLICATE KEY
UPDATE name = VALUES(name);
SELECT * FROM testproc;
END
If specified idproc value exists in id column the row will be updated, if not then the new row will be inserted.
Additionally - I recommend you to provide NULL value instead of zero when you want to insert new row with specified nameproc value. NULL always cause autoincremented primary key generation whereas zero needs in specific server option setting.

issue with create table inside if/else block

I'm trying to create a table in a MySQL stored procedure depending upon the values of some of the passed parameters. My code is as follows:
DELIMITER //
CREATE PROCEDURE testifelse(IN CurrentGPA varchar(40), IN CurrentGPAValue varchar(40))
BEGIN
IF CurrentGPAValue IS NULL THEN CREATE TABLE tableCurrentGPA(SELECT DISTINCT u.user_id AS uid FROM users u);
ELSE CREATE TABLE tableCurrentGPA(SELECT DISTINCT udata.user_id AS uid FROM userdata udata WHERE udata.userDataTypeName = CurrentGPA AND udata.userDataText = CurrentGPAValue);
END
I'm getting an error stating: #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 5.
I'm not sure what I've done wrong here. The syntax looks fine to me and the queries seem well-formulated.
You're missing the END IF statement.
CREATE PROCEDURE testifelse(IN CurrentGPA varchar(40), IN CurrentGPAValue varchar(40))
BEGIN
IF CurrentGPAValue IS NULL THEN CREATE TABLE tableCurrentGPA(SELECT DISTINCT u.user_id AS uid FROM users u);
ELSE CREATE TABLE tableCurrentGPA(SELECT DISTINCT udata.user_id AS uid FROM userdata udata WHERE udata.userDataTypeName = CurrentGPA AND udata.userDataText = CurrentGPAValue);
END IF;
END

Weird issue with a stored procedure in MySQL

I need to add a new stored procedure on our company's MySQL server. Since it's just slightly different, I used an already existing one, added the additional field and changed the name of the procedure. The weird thing now is that when I want to execute the statement, it returns:
Error Code: 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 3
reffering to the 0 in this line: SET #update_id := 0; What makes it weird is, that I queried that stored procedure by using SHOW CREATE PROCEDURE . It's saved in our database and is working fine. I just can't use it as a new stored procedure (no matter if I try to apply it to the new test database or if I use it on the existing database by giving it a new name).
I searched the internet for a solution. Unfortunately to no avail. I even set up a new database with a new table and some demo values where I tried to execute the original, unaltered stored procedure. It returns the exact same error.
Here's the currently used and working stored procedure I'm talking about:
CREATE DEFINER=`root`#`localhost` PROCEDURE `customer_getcard`(IN Iinstance INT, IN Itimebuy DOUBLE, IN Iprice DECIMAL(10,2), IN Itariff INT, IN Icomment VARCHAR(128))
BEGIN
SET #update_id := 0;
UPDATE customer_shop SET state = 1, id = (SELECT #update_id := id), instance=Iinstance, timebuy=Itimebuy, price=Iprice, comment=Icomment WHERE tariff=Itariff AND state = 0 LIMIT 1;
SELECT * FROM customer_shop WHERE id = #update_id;
END
I hope you guys can help me as I am completely out of ideas what's wrong. :/
Regards, Mark
You need to define an alternative command delimiter, as MySQL currently thinks your CREATE PROCEDURE command ends at the first ; it encounters (on line 3, after the 0), which would be a syntax error as it's after a BEGIN but before the corresponding END:
DELIMITER ;; -- or anything else you like
CREATE PROCEDURE
...
END;; -- use the new delimiter you chose above here
DELIMITER ; -- reset to normal
MySQL stored procedures do not use ":=" for value assignment, just use "=".
Also don't think "id = (SELECT #update_id := id)" is acceptable. Here's an alternative solution (untested):
CREATE DEFINER=`root`#`localhost` PROCEDURE `customer_getcard`(IN Iinstance INT, IN Itimebuy DOUBLE, IN Iprice DECIMAL(10,2), IN Itariff INT, IN Icomment VARCHAR(128))
BEGIN
select id into #update_id from customer_shop WHERE tariff=Itariff AND state = 0 LIMIT 1;
UPDATE customer_shop SET state = 1, instance=Iinstance, timebuy=Itimebuy, price=Iprice, comment=Icomment where id = #update_id;
SELECT * FROM customer_shop WHERE id = #update_id;
END
You may also want to put error handlers in case there's no matching row to be edited.

MySQL Stored Procedure Declare Issue

This problem has cost me almost an hour now and I know it is something simple.
I am getting 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 'IN VARCHAR(256), hl7PatientId IN VARCHAR(256))
BEGIN
DECLARE mainQueue INT' at line 1
Here is my query which looks right to me:
DROP PROCEDURE IF EXISTS insert_data;
CREATE PROCEDURE `insert_data`(hl7PatientName IN VARCHAR(256), hl7PatientId IN VARCHAR(256))
BEGIN
DECLARE mainQueue INT DEFAULT 1;
SELECT `queueid` INTO mainQueue FROM `queues` WHERE `description` LIKE 'Main' AND `enabled` = 1 LIMIT 1;
INSERT INTO `queue_data`
(`queueid`, `patientname`, `patientid`, `location`, `creationtime`, `priority`)
VALUES
(mainQueue, hl7PatientName, hl7PatientId, 'QUEUE_NUMBER', TIMESTAMP(), '');
END;
I am using MySQL 5.0.77 for this.
Can anybody see anything in this that is wrong?
i've tidied up your example a little - note the use of delimiter and in params !
drop procedure if exists insert_queue_data;
delimiter #
create procedure insert_queue_data
(
in p_patientname varchar(255), -- size ? i always prefix my params p_ and keep the same name as the db field
in p_patientid varchar(255) -- size ? are you sure this isnt an integer ?
)
begin
-- i always prefix my variables v_ and keep same name as the db field
declare v_queueid int unsigned default 1;
select queueid into v_queueid from queues where
description like 'Main' and enabled = 1 limit 1;
insert into queue_data(queueid, patientname, patientid, location, creationtime, priority) values
(v_queueid, p_patientname, p_patientid, 'QUEUE_NUMBER', now(), '');
end#
delimiter ;
Reverse the order of IN and parameter name.
...(IN hl7PatientName VARCHAR(256), IN hl7PatientId VARCHAR(256))...