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

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.

Related

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.

GROUP_CONCAT as input of MySQL function

Is it possible to use a GROUP_CONCAT in a SELECT as the input of a MySQL function? I cannot figure out how to cast the variable it seems. I've tried blob. I've tried text (then using another function to break it up into a result set, here) but I haven't had any success.
I want to use it like this:
SELECT
newCustomerCount(GROUP_CONCAT(DISTINCT items.invoicenumber)) AS new_customers
FROM items;
Here is the function:
DROP FUNCTION IF EXISTS newCustomerCount;
DELIMITER $$
CREATE FUNCTION newCustomerCount(invoicenumbers BLOB)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE new_customers INT;
SET new_customers = 0;
SELECT
SUM(nc.record) INTO new_customers
FROM (
SELECT
1 AS customer,
(SELECT COUNT(*) FROM person_to_invoice ps2 WHERE person_id = ps1.person_id AND invoice < ps1.invoice) AS previous_invoices
FROM person_to_invoice ps1
WHERE invoice IN(invoicenumbers)
HAVING previous_invoices = 0
) nc;
RETURN new_customers;
END$$
DELIMITER ;
Because Mysql functions do not support dynamic queries, I recommend you re-think your basic strategy to pass in a list of invoice numbers to your function. Instead, you could modify your function to accept a single invoice number and return the number of new customers just for the one invoice number.
Also, there are some optimizations you can make in your query for finding the number of new customers.
DROP FUNCTION IF EXISTS newCustomerCount;
DELIMITER $$
CREATE FUNCTION newCustomerCount(p_invoice INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE new_customers INT;
SET new_customers = 0;
SELECT
COUNT(DISTINCT ps1.person_id) INTO new_customers
FROM
person_to_invoice ps1
WHERE
ps1.invoice = p_invoice
AND NOT EXISTS (
SELECT 1
FROM person_to_invoice ps2
WHERE ps1.person_id = ps2.person_id
AND ps2.invoice < ps1.invoice
);
RETURN new_customers;
END$$
DELIMITER ;
Then you can still get the total number of new customers for a given list of invoice numbers like this:
SELECT
SUM(newCustomerCount(invoice)) as total_new_customers
FROM items
WHERE ...
You could try FIND_IN_SET() instead of IN(). The performance will probably be horrible when passing in a long list of invoice numbers. But it should work.
WHERE FIND_IN_SET(invoice, invoicenumbers)
You are looking in the wrong place.
WHERE invoice IN(invoicenumbers) will not do the desired substitution. Instead you need to use CONCAT to construct the SQL, then prepare and execute it.

MySQL Syntax : "the right syntax to use near" - right in the beginning

I am a MySQL-noob and today I tried to setup a MySQL call which is more than 5 lines long. I keep getting syntax errors which I try to fix for hours, but I don't have a clue what the problem is. Here is the code:
USE myDatabase;
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
SET #ID = 1;
SET #maxID = 3;
CREATE TEMPORARY TABLE resultTable(v DOUBLE, ttc DOUBLE);
WHILE (#ID < #maxID) DO
INSERT partTable1.v, partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID)) as partTable1)
INNER JOIN
((SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID)) as partTable2) ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)))
);
SET #ID := #ID + 1;
END WHILE;
END //
DELIMITER;
CALL MYPROC();
SELECT * FROM resultTable LIMIT 100;
Is there anything obvious that needs to be corrected?
Update1: Added semicolon to the "CREATE.."-statement, now first three statements are OK.
Update2: Added 3 more semicolons!
Update3: Followed the suggestion to make it a function + separate function call. Error message changed!
Update4: I fixed the issues mentioned in the two answers. Still something wrong there. See updated code above and error message below.
Updated error message:
ERROR 1064 (42000) at line 4: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear ' partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELE' at line 11
Kind Regards,
Theo
Flow control statements, of which WHILE is one, can only be used within a stored procedure, but you are attempting to use it as a plain query via the console.
If you absolutely must take this path (using mysql instead of an application language), create a store procedure with the code you want, then call it.
Creating the procedure would look like this:
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
WHILE (#ID < #maxID) DO
SET #partTable1 = (SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID));
SET #partTable2 = (SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID));
INSERT v, ttc INTO resultTable FROM
(#partTable1 INNER JOIN #partTable2 ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)));
SET #ID := #ID + 1;
END WHILE;
END//
DELIMITER ;
Then to call it:
CALL MYPROC();
See this SQLFiddle of a simplified version of this working.
Note that you do have one syntax error:
#ID = #ID + 1; -- incorrect syntax
SET #ID := #ID + 1; -- correct
Still some syntactic problems and functionality problems...
You can't use WHILE in SQL scripts. You can use WHILE only in the body of a stored routine. See http://dev.mysql.com/doc/refman/5.6/en/flow-control-statements.html
You can't use SET to assign multiple columns to a scalar. MySQL doesn't support relation-valued variables, only scalar variables. See http://dev.mysql.com/doc/refman/5.6/en/set-statement.html
You can INSERT from the results of a query with a join, but the query must be introduced with SELECT. See http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
You can't use session variables as the names of tables. You would have to use a prepared statement. See http://dev.mysql.com/doc/refman/5.6/en/prepare.html But that opens a whole different can of worms, and doing it wrong can be a security vulnerability (see http://xkcd.com/327). I wouldn't recommend you start using prepared statements as a self-described MySQL-noob.
This problem is probably simpler than you're making it. You don't need a temporary table, and you don't need to read the results one row at a time.
Here's an example that I think does what you intend:
USE myDatabase
SET #ID = 1;
SET #maxID = 3;
SELECT sp.v, si.ttc
FROM speedTable AS sp
INNER JOIN sightsTable AS si
ON (sp.trip_id = si.trip_id AND 0.04 > ABS(sp.time_sec - si.time_sec))
WHERE sp.trip_id BETWEEN #ID AND #maxID;

Trying to get Count single value from mysql stored procedure

I am trying to do a count in a mysql stored procedure but cant get the syntax right help1
delimiter//
create procedure get_count_workmen_type(
IN employee_payroll int,
OUT mycount int
)
begin
SELECT count(*) into mycount from workman
where employee_payroll = employee_payroll
end //
delimiter;
You should prefix your parameter names (personally I use "p_") to differentiate them from column names, etc. For example where employee_payroll = employee_payroll will always be true because it's comparing the column to itself.
Also you should add a semi-colon to the end of your select statement.
Putting those two changes together gives you something like this:
delimiter //
create procedure get_count_workmen_type(
IN p_employee_payroll int,
OUT p_mycount int
)
begin
SELECT count(*)
into p_mycount
from workman
where employee_payroll = p_employee_payroll;
end //
delimiter ;

Assigning the value from a select statement to a vairable in MySQL

I'm fairly new to SQL in general and even more so to MySQL and I've hit a stumbling block. I'm attempting to use a procedure to copy the value of one field to another if the original field is not null, this procedure is then called by triggers whenever the table is updated or has a new row inserted into it. Here is what I have so far:
-- WORK_NOTES_PROCEDURE - This copies the contents of the estimate notes to the work order notes if the original estimate had any notes with it.
DROP PROCEDURE IF EXISTS 'WORK_NOTES_PROCEDURE';
DELIMITER $$
CREATE PROCEDURE WORK_NOTES_PROCEDURE()
BEGIN
DECLARE var_temp VARCHAR(50);
SET var_temp := (SELECT ESTIMATE_NOTES FROM ESTIMATES WHERE ESTIMATES.ESTIMATE_NUMBER = WORK_ORDERS.ESTIMATE_NUMBER);
IF var_temp IS NOT NULL THEN
UPDATE WORK_ORDERS SET WORK_ORDER_NOTES = var_temp WHERE WORK_ORDERS.ESTIMATE NUMBER = ESTIMATES.ESTIMATE_NUMBER;
END IF;
END$$
DELIMITER ;
Absolutely any help would be appreciated, the error I'm getting is a syntax error for the line where I'm assigning a value to var_temp.
try,
SET var_temp = (SELECT ESTIMATE_NOTES
FROM ESTIMATES INNER JOIN WORK_ORDERS
ON ESTIMATES.ESTIMATE_NUMBER = WORK_ORDERS.ESTIMATE_NUMBER
LIMIT 1);