Create Stored Procedure in MySQL - mysql

i have the following syntax for creating a stored procedure in MySQL 5.0.10
delimiter //
CREATE PROCEDURE getTweets (var1 varchar(100))
LANGUAGE SQL
SQL SECURITY DEFINER
COMMENT 'A procedure to return 20 least scored tweets based on the temp sessionid of the user'
BEGIN
SELECT count(ts.tweetid) as "count",t.id as "tweetid", t.tweettext as "tweet"
FROM tweets t
LEFT JOIN tweetscores ts ON t.id = ts.tweetid
where t.id not in (select distinct(tweetid) from tweetscores where temp_sessionid=var1)
group by t.id, t.tweettext order by count
LIMIT 10;
END//
i keep on getting the 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
can anybody spot the error..

Your query works when executing it as a script on DB level.
But using PhpMyAdmin you need remove the delimiter statement.
CREATE PROCEDURE getTweets (var1 varchar(100))
LANGUAGE SQL
SQL SECURITY DEFINER
COMMENT 'A procedure to return 20 least scored tweets based on the temp sessionid of the user'
BEGIN
SELECT count(ts.tweetid) as "count",t.id as "tweetid", t.tweettext as "tweet"
FROM tweets t
LEFT JOIN tweetscores ts ON t.id = ts.tweetid
where t.id not in (select distinct(tweetid) from tweetscores where temp_sessionid=var1)
group by t.id, t.tweettext order by count
LIMIT 10;
end
PhpMyAdmin will do the rest for you.

CREATE PROCEDURE getTweets (var1 varchar(100))
LANGUAGE SQL
SQL SECURITY DEFINER
COMMENT 'A procedure to return 20 least scored tweets based on the temp sessionid of the user'
BEGIN
SELECT count(ts.tweetid) as "count",t.id as "tweetid", t.tweettext as "tweet"
FROM tweets t
LEFT JOIN tweetscores ts ON t.id = ts.tweetid
where t.id not in (select distinct(tweetid) from tweetscores where temp_sessionid=var1)
group by t.id, t.tweettext order by count
LIMIT 10;
end

Related

"Delimiter" is not valid at this position, expecting CREATE

I was getting an error of "Delimiter" is not valid at this position, expecting CREATE" as I was writing a stored procedure and couldn't figure out the cause. I think it might be an issue with MySQL workbench possibly, because the following code gives the same error but was copied straight off of this website.
DELIMITER $$
CREATE PROCEDURE GetTotalOrder()
BEGIN
DECLARE totalOrder INT DEFAULT 0;
SELECT COUNT(*)
INTO totalOrder
FROM orders;
SELECT totalOrder;
END$$
DELIMITER ;
Edit: My real stored procedure is:
DELIMITER //
CREATE PROCEDURE GetSimilar(inputdate char(10))
BEGIN
Declare id(tinyint) DEFAULT 0;
Set id := (select t.IdTimelineinfo
From timelineinfo t
WHERE t.Date = inputdate);
SELECT t.Date From timelineinfo t where t.date = inputdate;
SELECT o.Name, o.Race, o.Sex, o.IdOfficer
FROM timelineinfo
JOIN timelineinfo_officer ON timelineinfo.IdTimelineinfo = timelineinfo_officer.IdTimelineinfo
JOIN officers o ON timelineinfo_officer.IdOfficer = o.IdOfficer
WHERE timelineinfo.IdTimelineinfo = id
UNION
SELECT s.IdSubject, s.Name, s.Race, s.Sex
FROM timelineinfo
JOIN timelineinfo_subject ON timelineinfo.IdTimelineinfo = timelineinfo_subject.IdTimelineinfo
JOIN subjects s ON timelineinfo_subject.IdSubject = s.IdSubject
WHERE timelineinfo.IdTimelineinfo = id;
UNION
Select *
From media m
Where (m.IdTimelineinfo = id);
END //
DELIMITER ;
Watch out where you edit the procedure SQL code. There's a dedicated routine object editor (just like there are for tables, triggers, views etc.), which only accept SQL code for their associated object type. Hence they don't need a delimiter and even signal an error if you use one.
On the other hand you can always directly edit SQL code in the SQL IDE code editors, where no such special handling is implemented. In this case you need the delimiter.

Error while returning multiple ResulSets from a stored procedure in MySQL

Here's shortened script of my stored procedure:
DROP PROCEDURE IF EXISTS `GetVehicleDetails`;
DELIMITER //
CREATE PROCEDURE `GetVehicleDetails`(
IN `inRefNo` VARCHAR(30) COLLATE utf8mb4_general_ci,
IN `inSurveyType` VARCHAR(20) COLLATE utf8mb4_general_ci
)
BEGIN
DECLARE vehicleTypeID VARCHAR(2);
SET FOREIGN_KEY_CHECKS = OFF;
SELECT * FROM vehicle_details V
LEFT JOIN vehicle_types VT ON VT.TypeID = V.VehicleType
LEFT JOIN vehicle_makes VM ON VM.TypeID = V.VehicleType AND VM.MakeID = V.VehicleMake
LEFT JOIN vehicle_models VD
ON VD.TypeID = V.VehicleType AND VD.MakeID = V.VehicleMake AND VD.ModelID = V.VehicleModel
LEFT JOIN vehicle_variants VV
ON VV.TypeID = V.VehicleType
AND VV.MakeID = V.VehicleMake
AND VV.ModelID = V.VehicleModel
AND VV.VariantID = V.VehicleVariant
LEFT JOIN vehicle_body_types VB ON VB.BodyTypeID = V.TypeOfBody
LEFT JOIN vehicle_info_preinspection VP ON VP.RefNo = inRefNo
LEFT JOIN fuel_types F ON F.FuelTypeID = VP.Fuel
WHERE V.RefNo = inRefNo;
# Fetch Vehicle Type
SELECT VehicleType INTO vehicleTypeID FROM vehicle_details WHERE RefNo = inRefNo;
# Get details of body parts
IF vehicleTypeID = 1 THEN /* Personal Car */
SELECT * FROM body_parts_personal_car WHERE RefNo = inRefNo;
/*IF inSurveyType = 'preinspection' THEN
SELECT * FROM accessories_personal_car WHERE RefNo = inRefNo;
END IF;*/
ELSEIF vehicleTypeID = 4 THEN /* 2 Wheeler */
SELECT * FROM body_parts_2_wheeler WHERE RefNo = inRefNo;
ELSE
SELECT * FROM body_parts_commercial_vehicle WHERE RefNo = inRefNo;
END IF;
SET FOREIGN_KEY_CHECKS = ON;
END//
DELIMITER ;
Now, while executing the stored procedure with this statement:
CALL GetVehicleDetails('some ref no', 'interim-survey');
an error is being thrown:
Static analysis:
1 errors were found during analysis.
Missing expression. (near "ON" at position 25)
SQL query: Edit Edit
SET FOREIGN_KEY_CHECKS = ON;
MySQL said: Documentation
2014 - Commands out of sync; you can't run this command now
I have noticed that the stored procedure is throwing on second SELECT statement -
SELECT * FROM body_parts_personal_car WHERE RefNo = inRefNo;
in my case. Even if I write SELECT Now(); or SELECT vehicleTypeID; before it, the stored procedure throws the same error. If I comment this SELECT statement out, the stored procedure WORKS.
The same stored procedure works on localhost perfectly. I am using phpMyAdmin on remote server to maintain my database.
Any help please?
EDIT: I am receiving same problem in all stored procedures which have multiple SELECT statements to be returned back as ResultSet.
And, if I click Execute from the list of stored procedures in phpMyAdmin, the stored procedure executes. But if I invoke the stored procedure with CALL <proc_name()>;, the above error is displayed.
The "Commands out of sync" error usually indicates the client side error (results from the previous result set have not been processed and remain in the buffer).
If you are running the procedure from the phpMyAdmin, note that phpMyAdmin does not know to handle procedures returning multiple result sets. Try to run the command from MySQL command prompt and see if you get any errors.
The procedure itself looks ok, apart from unnecessary SET FOREIGN_KEY_CHECKS-commands (the procedure does not do any update/insert).
There problem was with one or more of tables involved in the procedure. Some queries and procedure calls inside a procedure were giving errors as "illegal mix of collations xxxxxxxx". I had to set COLLATIONS of all char/varchar/enum fields of tables and parameters of procedures giving errors to utf8mb4_general_ci.

mysql syntax error on creating stored procedure

There are tons of similar posts, but still couldn't solve the error.
Here's my stored procedure query:
DROP PROCEDURE IF EXISTS spa_gui_get_next_task;
DELIMITER //
CREATE PROCEDURE `spa_gui_get_next_task`(IN var_user_id INT(11), IN var_task_id INT(11))
BEGIN
-- create temp table
CREATE TEMPORARY TABLE temp_table_user_tasks engine=memory
SELECT
tsk.id,
tsk.request_id,
tsk.sys_index,
tsk.category_group,
tsk.category,
tsk.is_assigned,
tsk.hash_id
FROM
user_tasks as usr
inner join
unassigned_tasks as tsk
on usr.task_id = tsk.id
WHERE
usr.assigned_to = var_user_id
AND
tsk.product_id NOT IN ( SELECT product_id FROM product_progresses WHERE request_id = tsk.request_id )
AND
BINARY hash_id NOT IN ( SELECT hash_id FROM product_match_unmatches WHERE request_id = tsk.request_id AND (is_matched=1 OR auto_unmatched_by IS NOT NULL) )
ORDER BY tsk.id;
-- fetch next row
SELECT qs.*
FROM temp_table_user_tasks as qs
WHERE qs.id = ( SELECT min(qs.id) FROM temp_table_user_tasks as qt WHERE qt.id > var_task_id);
-- drop temp table
DROP TEMPORARY TABLE IF EXISTS temp_table_user_tasks;
END //
DELIMITER ;
I am getting this 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 'DELIMITER //
CREATE PROCEDURE `spa_gui_get_next_task`(IN var_user_id INT(11), ' at line 1
Also the same query is working on phpmyadmin 10.1.26-MariaDB, and even tried exporting the same stored procedure from phpmyadmin to another mysql v5.7.12.

Syntax error when creating procedure in mysql

I have this query.
SELECT distinct c.reportingDate, c.clientId
FROM clients AS c
WHERE NOT EXISTS
( SELECT 1
FROM accounts_europe AS e
WHERE e.reportingDate = c.reportingDate
AND e.clientId = c.clientId
union
SELECT 1 -- line A. unexpected select error
FROM accounts_usa AS u
WHERE u.reportingDate = c.reportingDate
AND u.clientId = c.clientId
) ;
when executing it at mysql workbench it displays a syntax error which says "unexpected select" at line A.
However, since the query is right, when I execute it, it indeed executes and returns the correct results.
When I try to create a procedure that contains the exact same thing, it cannot be compiled. The source code is this:
CREATE PROCEDURE `proc_sample`()
BEGIN
SELECT distinct c.reportingDate, c.clientId
FROM clients AS c
WHERE NOT EXISTS
( SELECT 1
FROM accounts_europe AS e
WHERE e.reportingDate = c.reportingDate
AND e.clientId = c.clientId
union
SELECT 1 -- line A. unexpected select error
FROM accounts_usa AS u
WHERE u.reportingDate = c.reportingDate
AND u.clientId = c.clientId
) ;
END
The message displayed is "The object's DDL statement contains syntax errors."
Is it something I am doing wrong about this or is it a bug of the mysql workbench?
This error comes up because of a MySQL grammar bug* that has been fixed meanwhile. Try the latest Workbench version instead (currently WB 8.0.11 RC, see "Development Releases" on the download page). That should work for you.
(*) MySQL Workbench uses ANTLR4 for parsing SQL code. That requires a MySQL grammar to generate the parser.
Your query is correct syntactically. It's maybe a workbench's bug. Coming to Stored Procedure, you should be able to create it with that query. Try creating SP using below query. In my case, I am able to create SP using this. Copy this query open a new query editor in the workbench and paste it there, select all and press Ctrl + Shift + Enter
USE `YOUR_DB`;
DROP procedure IF EXISTS `proc_sample`;
DELIMITER $$
USE `YOUR_DB`$$
CREATE DEFINER=`admin`#`%` PROCEDURE `proc_sample`()
BEGIN
SELECT distinct c.reportingDate, c.clientId
FROM clients AS c
WHERE NOT EXISTS
( SELECT 1
FROM accounts_europe AS e
WHERE e.reportingDate = c.reportingDate
AND e.clientId = c.clientId
union
SELECT 1
FROM accounts_usa AS u
WHERE u.reportingDate = c.reportingDate
AND u.clientId = c.clientId
) ;
END$$
DELIMITER ;

SQL If Statment / select into in a stored procedure

I cannot understand why the following SQL procedure will not store on my database and is reporting an error, I've been at it for ages and am totally puzzled.
DELIMITER $$
CREATE PROCEDURE add_brand(IN inBrandName TEXT)
BEGIN
DECLARE brandexists INT DEFAULT 0;
SELECT count(*) WHERE BrandName = inBrandName INTO brandexists;
IF brandexists = 1 THEN
select "exists";
ELSE
INSERT INTO tblBrand (BrandName) VALUES (inBrandName);
SELECT LAST_INSERT_ID();
END IF;
END
The error i'm getting is this:
#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 'WHERE BrandName = inBrandName INTO brandexists; IF brandexists = 1 THEN sele' at line 6
any ideas?
You are missing a table where you select from:
SELECT count(*) WHERE BrandName = inBrandName INTO brandexists;
^---here (from some_table)