Syntax error in MySQL procedure while using if else insert query - mysql

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.

Related

What is the issue with this trigger (for the right syntax to use near '' )

Please I did this trigger to update table rating after each insert when 2 columns (id_prof,id_etud) inserted are already in the table but it gives mi this error
> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 6
The trigger :
CREATE TRIGGER Before_Insert_Rate
BEFORE INSERT ON rating
FOR EACH ROW
BEGIN
IF (EXISTS(SELECT * FROM rating WHERE id_prof=NEW.id_prof and id_etud = NEW.id_etud)) THEN
UPDATE `rating` SET `rate` = NEW.rate WHERE `id_prof` = NEW.id_prof and `id_etud` = NEW.id_etud;
ELSE INSERT INTO rating VALUES (NEW.idprof,New.rate,New.id_etud);
END IF
END
DELIMITER ;
You must set the DELIMITER before. Change it to:
DELIMITER //
CREATE TRIGGER Before_Insert_Rate
BEFORE INSERT ON rating
FOR EACH ROW
BEGIN
IF (EXISTS(SELECT * FROM rating WHERE id_prof=NEW.id_prof and id_etud = NEW.id_etud)) THEN
UPDATE `rating` SET `rate` = NEW.rate WHERE `id_prof` = NEW.id_prof and `id_etud` = NEW.id_etud;
ELSE INSERT INTO rating VALUES (NEW.idprof,New.rate,New.id_etud);
END IF
END; //
DELIMITER ;
from the official reference manual.
A trigger can access both old and new data in its own table. A trigger
can also affect other tables, but it is not permitted to modify a
table that is already being used (for reading or writing) by the
statement that invoked the function or trigger.
This means no query on table X can INSERT, UPDATE, or DELETE from table X; it also means that if a trigger on table X modifies table Y, it will fail for any query using both table X and Y that "triggers" it.
Example: UPDATE x INNER JOIN y ON x.id = y.id SET x.something = 1, y.something = 2 will cause a BEFORE UPDATE ON x trigger (that updates, inserts, or deletes from y) to fail.
I solved it using ON DUPLICATE KEY on a query instead of trigger
CREATE TABLE `rating` (
`id_prof` int(11) NOT NULL,
`rate` float NOT NULL,
`id_etud` int(11) NOT NULL,
UNIQUE (id_prof,id_etud)
)
the query :
INSERT INTO rating (id_prof,rate,id_etud) VALUES (1,2,5)
ON DUPLICATE KEY UPDATE rate=2

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the error:
SQL 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

mysql, syntax issue in procedure

I have problems with syntax in mysql procedure
CREATE PROCEDURE savep(
IN p_uuid VARCHAR(36),
IN p_sp INTEGER,
IN p_cd VARCHAR(250)
)
BEGIN
INSERT INTO maintable
(
uuid,
sp,
cd,
last_time_saved
)
VALUES
(
p_uuid,
p_sp,
p_cd,
now()
)
ON DUPLICATE KEY UPDATE
sp = VALUES(p_sp),
cd = VALUES(p_cd),
cd = VALUES(now()); -- syntaxerror, unexcepted NOW_SYM
END -- syntax error, unexcepted END
what am i doing wrong? uuid is a primary key in the main table.
Two minor things I can see.
You have no delimiter set at the top (but you might have that in the version you are trying to use).
Secondly you are setting cd twice in the on duplicate key clause, and one of those is setting it to VALUES(now()) , where what should be in the brackets is the name of a column whose value from the VALUES clause of the insert that you are setting it to.
Try this:-
DELIMITER //
CREATE PROCEDURE savep(
IN p_uuid VARCHAR(36),
IN p_sp INTEGER,
IN p_cd VARCHAR(250)
)
BEGIN
INSERT INTO maintable
(
uuid,
sp,
cd,
last_time_saved
)
VALUES
(
p_uuid,
p_sp,
p_cd,
now()
)
ON DUPLICATE KEY UPDATE
sp = VALUES(p_sp),
cd = VALUES(p_cd),
last_time_saved = now();
END

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

Get the Unique ID for the Last Inserted Row

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
-- ...