At the moment I'm trying to create a procedure in my databse with this query:
CREATE PROCEDURE InsertTitle(title VARCHAR(50), interpret VARCHAR(50), album VARCHAR(50))
BEGIN
INSERT IGNORE INTO Interpret (Name) VALUES (interpret);
SET #idInterpret := (SELECT id FROM Interpret WHERE Name = interpret);
INSERT IGNORE INTO Album (Name, Interpret) VALUES (#album, #idInterpret);
SET #idAlbum := (SELECT id FROM Interpret WHERE Name = album AND Interpret = #idInterpret);
INSERT INTO Lied (Name, Album, Interpret) VALUES (title, #idAlbum, #idInterpret,);
END;
But now I get the following error which doesn't tell my anything:
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
Do you have an idea where my mistake is? I use a MySQL server.
First, your problem might just be a delimited. Second, you are approaching the calculation of the inserted id incorrectly. You should use LAST_INSERT_ID():
DELIMITER $$
CREATE PROCEDURE InsertTitle(title VARCHAR(50), interpret VARCHAR(50), album VARCHAR(50))
BEGIN
INSERT IGNORE INTO Interpret (Name)
VALUES (interpret);
SELECT #idInterpret :-= LAST_INSERT_ID()
INSERT IGNORE INTO Album (Name, Interpret)
VALUES (#album, #idInterpret);
SELECT #idAlbum := LAST_INSERT_ID()
INSERT INTO Lied (Name, Album, Interpret)
VALUES (title, #idAlbum, #idInterpret);
END;
$$
DELIMITER ;
Also, set uses =, not :=. The latter is only needed in SELECT statements. And, you had an extra comma in the last VALUES() statement.
Try to use this solution:
delimiter //
CREATE PROCEDURE InsertTitle(title VARCHAR(50), interpret VARCHAR(50), album VARCHAR(50))
BEGIN
INSERT IGNORE INTO Interpret (Name) VALUES (interpret);
SET #idInterpret := (SELECT id FROM Interpret WHERE Name = interpret);
INSERT IGNORE INTO Album (Name, Interpret) VALUES (#album, #idInterpret);
SET #idAlbum := (SELECT id FROM Interpret WHERE Name = album AND Interpret = #idInterpret);
INSERT INTO Lied (Name, Album, Interpret) VALUES (title, #idAlbum, #idInterpret,);
END//
delimiter ;
For more details please see: MySQL CREATE PROCEDURE
Related
I have created one stored procedure which inserts a record into table and gets auto incremented ID of that record. Here I am getting an syntax error while setting LAST_INSERT_ID() into a variable.
ERROR 1064 (42000): 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 ');
SET _orderId = SELECT LAST_INSERT_ID(); END' at line 5
Please help me to solve this issue. Thanks in Advance.
My code is like below:
DELIMITER //
CREATE PROCEDURE placeOrder(IN _cartId INT, IN _createdBy INT)
BEGIN
DECLARE _orderId INT;
-- insert into order
INSERT INTO `TBL_ORDER`(`DealerId`, `OrderNo`, `CreatedBy`)
VALUES ((SELECT DealerId FROM TBL_SHOPPING_CART WHERE Id = _cartId), UNIX_TIMESTAMP(), _createdBy));
SET _orderId = SELECT LAST_INSERT_ID();
END//
DELIMITER ;
Try this.
delimiter //
CREATE PROCEDURE placeOrder(IN _cartId INT,IN _createdBy INT)
BEGIN
SET #orderId = '';
-- insert into order
INSERT INTO `TBL_ORDER`(`DealerId`, `OrderNo`, `CreatedBy`) VALUES ((SELECT DealerId FROM TBL_SHOPPING_CART WHERE Id = _cartId),UNIX_TIMESTAMP(),_createdBy));
SELECT LAST_INSERT_ID() INTO #orderId;
END//
delimiter ;
OR
delimiter //
CREATE PROCEDURE placeOrder(IN _cartId INT,IN _createdBy INT)
BEGIN
-- insert into order
INSERT INTO `TBL_ORDER`(`DealerId`, `OrderNo`, `CreatedBy`) VALUES ((SELECT DealerId FROM TBL_SHOPPING_CART WHERE Id = _cartId),UNIX_TIMESTAMP(),_createdBy);
SELECT LAST_INSERT_ID() AS '_orderId ';
END//
delimiter ;
You should make sure that your application is not having a global connection or shared connection. As last_insert_it() will return the last generated AI value it can be from any table. Especially if your host application is using async TASKs
Consider following scenario
Your application saves gps location every second => generating new AI value
You're trying above SP to insert a value => Generating new AI value
Between your insert and read last_insert_id, your application logs gps location again and created new AI value.
Now guess what happens? you get the last inserted id from the gps table not from your SP.
usually insert's are fast, but assume your SP had to wait for a table lock and got delayed. In such case, you will receive wrong ID.
Safest way can be to escapsulate your SP work within a transaction and get the max value of your AI column (assuming it's an unsigned AI column).
Try:
...
-- SET _orderId = SELECT LAST_INSERT_ID();
SET _orderId = LAST_INSERT_ID();
SELECT _orderId;
...
or
...
-- SET _orderId = SELECT LAST_INSERT_ID();
SET _orderId = (SELECT LAST_INSERT_ID());
SELECT _orderId;
...
I have stored procedure for insert booking record with details like booking_id, name, r_id, t_id etc. Now I want to know how to retrieve insert id of this record.
Stored procedure allow LAST_INSERT_ID only.
Here MYSQL_INSERT_ID() not working.
But here at a time two users perform booking then last record is different.
Please help me how to get insert record id for the booking through Stored Procedures in my sql ..
You can capture the last_insert_id() value in different ways.
Define an 'OUT' parameter in procedure signature, with proper data type.
Now, after executing INSERT INTO..., execute set out_param := last_inser_id();
Now you can read value of 'OUT' parameter from the calling program or sql code body.
Example 1:
delimiter //
create procedure sp_so_q24075108( IN param1 int, ..., OUT param_auto_id int )
begin
insert
into table_name( col2, col3, ... )
values ( param1, param2, ... );
set param_auto_id := last_insert_id();
end;
//
delimiter ;
call sp_so_q24075108( 6, ..., #last_generated_id );
select #last_generated_id;
OR
Capture 'LAST_INSERT_ID()' into user variable after executing 'INSERT' statement.
Now you can read value of 'OUT' parameter from the calling program or sql code body.
Example 2:
delimiter //
create procedure sp_so_q24075108( IN param1 int, ... )
begin
insert
into table_name( col2, col3, ... )
values ( param1, param2, ... );
set #auto_id := last_insert_id();
end;
//
delimiter ;
call sp_so_q24075108( 6, ... );
select #auto_id;
Reference:
CREATE PROCEDURE Syntax
I have to create a stored procedure to add info into the Comments table, then add the commenters name into the Commenters name if it does not exist. I've been tweaking the code for quiet awhile now, and keep getting a syntax error at line 11.
Not sure I understand how to use IF NOT EXISTS syntax.
DELIMITER //
CREATE PROCEDURE AddComment(Name VARCHAR(60), Title VARCHAR(60), Comments VARCHAR(60))
BEGIN
INSERT INTO Comments(Name, Title, Comments)
VALUES (Name, Title, Comments);
IF NOT EXISTS(SELECT Name
FROM Commenters
WHERE Name = Name)
UPDATE Commenters
SET Name = Name;
END IF;
END;
//
Can anybody spot the problem with this stored procedure? mysql is reporting the following error:
1048 Column 'categoryID' cannot be null
DELIMITER $$
CREATE PROCEDURE catalogue_assign_product_to_subcategory(
IN inProductId INT,
IN insubCategoryId INT)
BEGIN
DECLARE catID INT;
SELECT subcategoryParent FROM tblSubcategory
WHERE subcategoryID = insubCategoryId INTO catID;
INSERT INTO tblProdCat (productID, categoryID)
VALUES (inProductId, 'catID');
END
'catID' should be without the singlequotes in the INSERT statement.
I guess the field is defined as INT, you now try to insert a STRING
INSERT INTO tblProdCat (productID, categoryID)
VALUES (inProductId, catID);
I am new to sql and most of my training is in MSSQL, however I am taking a class in MYSQL. I have a stored procedure that is giving me an issue. I have the delimiter set to //.
CREATE PROCEDURE AddComment
(
name varchar(50),
emailAddress varchar(50),
Comments text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT name into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS ('names', 'emailAddresses') values (name, emailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS ('commentersID', 'Comments') values (ComID, Comments);
END;
//
EDIT
This is what I have now:
CREATE PROCEDURE AddComment
(
Username varchar(50),
UseremailAddress varchar(50),
UserComment text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT Username into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS(names,emailAddresses) values (Username, UseremailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS(commentersID, Comments) values (ComID, UserComment);
END;
//
And the error I am getting is:
ERROR 1064 (42000): 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 'BEGIN INSERT INT
O COMMENTERS(names, emailAddresses) values (Username, Useremail' at line 1
Any Ideas?
You are coding column names and values reversed in you insert statements.
It should be
INSERT INTO COMMENTERS (name, emailAddress) values ('names', 'emailAddresses') ;