I have this MySQL query to create a stored procedure:
Delimiter //;
Create Procedure addUser(
IN facebookId varchar(20),
IN name varchar(50),
In accessToken varchar(100),
in expires float)
Begin
Declare invitingUsers Table(Id varchar(20));
Insert Into Users
(`Facebook_Id`,`Name`,`Access_Token`,`Expired`) Values (facebookId,name,accessToken,expires);
Select Inviting_Id
From Invited_Users
Where Invited_Id = facebookId
Into invitingUsers;
Update Table Users
Set Credit = Credit + 1
Where Facebook_Id In (Select Id From invitingUsers);
End//
but I'm keep getting this error - can't understand why:
#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 'Table(Id varchar(20)); Insert Into Users (`Facebook' at line 7
Change #1
Delimiter //; to Delimiter //
Change #2
Create a Temp Table in Memory
Change #3
Changed
Select Inviting_Id
From Invited_Users
Where Invited_Id = facebookId
Into invitingUsers;
into
INSERT INTO invitingUsers
Select Inviting_Id From Invited_Users
Where Invited_Id = facebookId;
With these changes I give you this:
Delimiter //
Create Procedure addUser(
IN facebookId varchar(20),
IN name varchar(50),
In accessToken varchar(100),
in expires float)
Begin
Declare invitingUsers Table(Id varchar(20));
Create temporary table if not exists invitingUsers
(Id varchar(20), PRIMARY KEY (id)) ENGINE=MEMORY;
Insert Into Users
(`Facebook_Id`,`Name`,`Access_Token`,`Expired`)
Values (facebookId,name,accessToken,expires);
INSERT INTO invitingUsers
Select Inviting_Id From Invited_Users
Where Invited_Id = facebookId;
Update Table Users
Set Credit = Credit + 1
Where Facebook_Id In (Select Id From invitingUsers);
End//
Delimiter ;
Give it a Try !!!
Related
Here is a sequence of very simple sql queries (MySQl 8.0)
drop table IF EXISTS stack_Compare;
drop table IF EXISTS lastNode;
CREATE TABLE stack_Compare (Station VARCHAR(20), Track INT);
CREATE TABLE lastNode (Last_Station_ID INT, I INT);
AlTER table lastNode ADD PRimary key (I);
INSERT INTO lastNode VALUES (1, 1);
Drop trigger IF EXISTS lastAdded;
DELIMITER $$
CREATE TRIGGER lastAdded AFTER INSERT
ON stack_Compare FOR EACH ROW
BEGIN
UPDATE lastNode SET Last_Station_ID = (SELECT Station.Station_ID FROM Station, stack_Compare WHERE New.Station = Station.Name) WHERE I = 1;
END $$
DELIMITER ;
DROP PROCEDURE IF EXISTS insertStation;
DROP PROCEDURE IF EXISTS insertMain;
DELIMITER $$
SET max_sp_recursion_depth=3;
CREATE PROCEDURE insertStation (insertstationID INT, starter VARCHAR(20), destination VARCHAR(20))
this_procedure:BEGIN
DECLARE nextNode INT DEFAULT NULL;
INSERT INTO stack_Compare (Station)
SELECT Name from Station WHERE Station_ID = insertstationID;
IF insertStationID IN (SELECT Station_ID FROM Station WHERE Name = destination)
THEN LEAVE this_procedure;
END IF;
SET nextNode = (SELECT Next_Station FROM Station WHERE Station_ID = insertstationID);
IF nextNode IS NULL
THEN LEAVE this_procedure;
END IF;
IF nextNode = -1
THEN LEAVE this_procedure;
ELSE CALL insertStation (nextNode, starter, destination);
END IF;
END
$$
CREATE PROCEDURE insertMain (starter VARCHAR(20), destination VARCHAR(20))
BEGIN
DECLARE nextNode INT DEFAULT NULL;
CALL insertStation(8, starter, destination);
loop1: LOOP
SET nextNode = (SELECT Station.Next_Station FROM Station, lastNode WHERE Station.Station_ID = lastNode.Last_Station_ID);
IF nextNode IN (SELECT Station_ID FROM Station WHERE Name = destination)
THEN LEAVE loop1;
END IF;
END LOOP loop1;
END;
$$
DELIMITER ;
CALL insertMain('G1','RG');
SELECT * FROM stack_Compare;
select * from lastNode;
and the station table is
So basically the query SELECT * FROM stackCompare should give
Station
G2
RG
But it only shows G2 in there and the error is Subquery returns more than 1 row
Which I am unable to find WHY from past few hours and a big project is stuck because of this. I guess after doing many experiments that there can be a problem with the Set nextNode line.
below are the queries to create and fill table.
CREATE TABLE Station (
Station_ID INT,
Name VARCHAR(20),
Line_ID INT,
Prev_Station INT,
Next_Station INT,
Hybrid_ID INT,
PRIMARY KEY (Station_ID),
FOREIGN KEY (Line_ID) REFERENCES Line(Line_ID),
FOREIGN KEY (Hybrid_ID) REFERENCES Hybrid(Hybrid_ID)
);
ALTER TABLE Station ADD FOREIGN KEY (Prev_Station) REFERENCES Station(Station_ID);
ALTER TABLE Station ADD FOREIGN KEY (Next_Station) REFERENCES Station(Station_ID);
INSERT INTO Station VALUES
(1,'R1',1,NULL,2,NULL),
(2,'R2',1,1,3,NULL),
(3,'RG',1,-1,-1,1),
(4,'RY',1,-1,-1,2),
(5,'R3',1,4,6,NULL),
(6,'R4',1,5,NULL,NULL),
(7,'G1',3,NULL,8,NULL),
(8,'G2',3,7,3,NULL),
(9,'Y1',2,NULL,4,NULL),
(10,'Y2',2,4,11,NULL),
(11,'Y3',2,10,NULL,NULL);
I try to create stored procedure in MySQL:
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int
select _authorId = id from Authors where name = _authorName
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName)
SELECT _authorId = SCOPE_IDENTITY()
END IF
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId)
END;
But I get the error:
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 'select _authorId = id from Authors where name = _authorName IF
(_authorId is nul' at line 1
Seems like script is too large to be executed. Line just broken near: IF (_authorId is null) THEN -- IF (_authorId is nul
You have a problem with your delimiters. By default it's ";". But you need internal delimiter, so :
DELIMITER |
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int;
select _authorId = id from Authors where name = _authorName;
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName);
SELECT _authorId = LAST_INSERT_ID();
END IF;
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId);
END|
Its working code on SQLYOG: Please try in this way
DELIMITER $$
CREATE /*[DEFINER = { user | CURRENT_USER }]*/ PROCEDURE `test`.`sp_attachAuthorToBook`(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
DECLARE _authorId INT;
SELECT id INTO _authorId FROM Authorss WHERE `name` = _authorName;
IF _authorId IS NULL THEN
INSERT INTO Authorss(`name`) SELECT _authorName;
SET _authorId = LAST_INSERT_ID();
END IF;
INSERT INTO Book_Authors(bookID, authorID) SELECT _bookId, _authorId;
END$$
DELIMITER ;
I already have a table employee with columns name(String),id(int),age(int).
I can't figure out where the syntax is wrong?
CREATE PROCEDURE recins (
name1 IN employee.name%type ,
id1 IN employee.id%type ,
age1 IN employee.age%type
) AS
BEGIN
INSERT INTO employee VALUES(name1,id1,age1);
END;
create table employee2
(
name varchar(100) not null,
id int not null,
age int not null
);
DELIMITER $$
CREATE PROCEDURE recins (
IN name1 varchar(100),
IN id1 int,
IN age1 int
)
BEGIN
INSERT INTO employee2 (name,id,age) VALUES(name1,id1,age1);
END $$
DELIMITER ;
-- test:
call recins('a',1,2);
delimiter is a special wrapper for stored procs, events, functions. Delimiter ; at the end of the stored proc sets it back to the normal/default delimiter of a semi-colon.
The above was tested.
In my Mysql , I have written below stored procedure to insert data into user table,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
When i test this procedure as below,
CALL `CreateUser1`('ab1#ansys.com' , 'abcdefgh' ,'abc#gmail.com', 'sa' , '' ,'123456789','hasghsdfhgfhgfhdgfhdsgsh');
SELECT * FROM `um.user` WHERE email='ab1#ansys.com';
It does nothing.
It doesn't insert data into table, I figured out the issue .
The isssue is in parameter "Email".
But when I change the parameter "Email" to "Email12" , it worked as expected.
But I don't want to change in parameter as it will be a change in my API as well,
Now i want to solve this issue in sp level as well, I have tried below changes as well in SP which also doesn't works,
Set #userEmail=Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=#userEmail)THEN
Any suggestions
Regards
Sangeetha
You may also qualify their identifiers. See 9.2.1 Identifier Qualifiers.
...
/*
-- You can also use Alias
SELECT `user_id`
FROM `um.user` `uu`
WHERE `uu`.`email` = `Email`
*/
IF NOT EXISTS (SELECT `user_id`
FROM `um.user`
WHERE `um.user`.`email` = `Email`) THEN
...
SQL Fiddle demo unqualified
SQL Fiddle demo qualified
Try this if you want to handle your issue within the stored procedure itself, without changing the name of parameter,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
DECLARE Email1 VARCHAR(50);
SET Email1 = Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email1)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
This is because in MySQL, the parameter name passed to a Stored Procedure should not be the same as Column Name. Hope this solves your problem :)
I created a stored procedure which should perform the following:
Insert into Agencies Table, creating an id in the PK index row
Save the id in a variable
Insert the id and other data into Users table
The syntax below does not trigger any errors:
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END
However, the Stored Proc doesn't insert my parameters into the tables when executed. So, after searching I try to create the SP like this (including $$ after "END" and resetting the delimiter to a semi-colon ):
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END $$
DELIMITER ;
MySql creates the Stored Proc but gives me 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 'DELIMITER' at line 1
When I execute the created Stored Proc it still doesn't insert the data in my parameters.
Any help would be appreciated.
Some problems in your stored procedure:
It is important to indicate the difference between 9.4. User-Defined Variables and routine parameters 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax, are different variables (eg.: aName != #aName).
Avoid naming parameters or variables as columns of your tables.
DELIMITER $$
CREATE PROCEDURE `insertNewAgencyAndAdmin` (
/*
IN `aName` varchar (100),
IN `numTrav` int,
IN `polType` int,
IN `uEmail` varchar(255),
IN `uFName` varchar(40),
IN `uLName` varchar(40),
IN `uTitle` varchar(100)
*/
IN `_aName` varchar (100),
IN `_numTrav` int,
IN `_polType` int,
IN `_uEmail` varchar(255),
IN `_uFName` varchar(40),
IN `_uLName` varchar(40),
IN `_uTitle` varchar(100)
)
BEGIN
/*
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
#`aName`,
#`numTrav`,
#`polType`
);
*/
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
`_aName`,
`_numTrav`,
`_polType`
);
/*
SET #`agencyID` = (SELECT `agencyID` from `btsAgency`.`Agencies` where `agencyID` = LAST_INSERT_ID());
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
#`agencyID`,
#`uEmail`,
#`uFName`,
#`uLName`,
#`uTitle`
);
*/
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
LAST_INSERT_ID(),
`_uEmail`,
`_uFName`,
`_uLName`,
`_uTitle`);
END$$
DELIMITER ;
SELECT * FROM discounts $$
delimiter $$;
CREATE PROCEDURE insertData(IN id int,IN title varchar(255),IN amount decimal)
BEGIN
insert into discounts values (id,title,amount);
END; $$
call insertData(3,"sadasd",56);
/*DROP PROCEDURE insertData */