Can't create stored procedure: Syntax error - mysql

I want to make a procedure that will insert user in table, but it should also check if user is 18 years old. I'm "doing" it with an if statement (p_datum_rodjenja is birth date of user). I'm not sure if my logic works because I cant create this procedure: when I try to run the query I got the following error:
Syntax error. Error code:1064.
Here is my code:
delimiter #
create procedure dodajKorisnikaProvjera
(
IN p_ime varchar(15),
IN p_prezime varchar(15),
IN p_broj_telefona int,
IN p_datum_rodjenja date,
IN p_broj_vozacke int,
IN p_grad_id int
)
BEGIN
if(TIMESTAMPDIFF(p_datum_rodjenja,CURDATE()) >18) then
INSERT into korisnik(
ime,
prezime,
broj_telefona,
datum_rodjenja,
broj_vozacke,
grad_id)
VALUES(
p_ime,
p_prezime,
p_broj_telefona,
p_datum_rodjenja,
p_broj_vozacke,
p_grad_id
);
else
select'Korisnik mora imati vise od 18 godina.';
end if;
END#
delimiter;

You are having error in Timestampdiff function.
Correct out it like this:
TIMESTAMPDIFF(year,p_datum_rodjenja,CURDATE()) >18)

Related

MySql syntax error on procedure parameter

I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.
I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:
DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (#id INT, #oldIndex INT, #newIndex INT)
BEGIN
DECLARE #swapID;
SET #swapID = (SELECT `id` FROM `product` WHERE `order_index` = #newIndex LIMIT 1);
UPDATE `products` SET `order_index` = (CASE WHEN `id` = #id THEN #newIndex
WHEN `id` = #swapID THEN #oldIndex END)
WHERE `id` IN (#id, #swapID);
END
I am using the option on phpMyAdmin to change the delimiter to /.
I receive a syntax error "near '#id INT, #oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.
You're using the Microsoft SQL Server convention of putting # before all the parameters and local variables. MySQL doesn't do this.
In MySQL syntax, procedure parameters have no sigil.
Also parameters are typically declared IN or OUT or INOUT.
CREATE PROCEDURE product_index_swap (IN id INT, IN oldIndex INT, IN newIndex INT)
BEGIN
DECLARE swapID;
...
MySQL variables that have the # sigil are session variables.
See also:
https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html
https://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html
https://dev.mysql.com/doc/refman/5.7/en/set-variable.html
In MySQL, the #var variables are session level variables.
Use normal variables without the # and make sure you do not have conflict with column names:
CREATE PROCEDURE product_index_swap (in_id INT, in_oldIndex INT, in_newIndex INT)
BEGIN
DECLARE v_swapID int;
SELECT id into v_swapID
FROM product
WHERE order_index = in_newIndex
LIMIT 1;
UPDATE products
SET order_index = CASE WHEN id = in_id THEN in_newIndex
WHEN id = v_swapID THEN in_oldIndex
END
WHERE id IN (in_id, v_swapID);
END

function that returns a table sql

I have this function:
DROP FUNCTION IF EXISTS MinCarAltezza;
DELIMITER $$
CREATE FUNCTION MinCarAltezza(altezza INT)
RETURNS SchedaTab TABLE(
Nome varchar(64),
Cognome varchar(64),
ID_Scheda int(10),
Sequenza int(2),
nSerie int(2),
nRipetizioni int(2),
Carico_Minimo decimal(4,1),
Esercizio varchar(30),
PRIMARY KEY(Nome,Cognome,Esercizio)
)
AS BEGIN
INSERT SchedaTab
SELECT DISTINCT U.Nome,U.Cognome,P.ID_Scheda,P.Sequenza,P.nSerie,
P.nRipetizioni,MIN(P.Carico),P.Esercizio
FROM utente AS U, scheda AS S, programma AS P
WHERE U.CF=S.ID_Utente AND S.ID_Scheda=P.ID_Scheda AND U.Altezza>altezza
AND P.Carico<>0
AND S.ID_Ist NOT IN(SELECT CF FROM istruttore WHERE Stipendio>500)
GROUP BY U.Nome,U.Cognome,S.ID_Scheda
RETURN
END $$
DELIMITER ;
that gives me an error in the line 4 where I declare the return type TABLE.
Is there something I'm missing?
That's the db if someone needs it: http://pastebin.com/DWYqVBpa
thank you
In MySQL there is no "table" data type, hence the error message. As MySQL documentation on stored functions says, return value can be
Any valid MySQL data type
Therefore, a stored function cannot return with a table. I would change the function into a stored procedure and
have a select statement at the end of the procedure (MySQL return the result of the last select)
or create a temporary table with the data and return the name of the temporary table in an out parameter

How do I create a stored procedure in MySQL that will select data and insert new values?

Hi I am trying to create a database that will check out document numbers per project. I am trying to keep the db server action limited to stored procedures.
The numbering system goes
XXXX-YY-ZZZZ
XXXX is the job number
YY is the document type table reference
ZZZZ is the document specific number and increments from 1 up for each type in each job...
Because of the numbering system, I can not use an auto incremented column... That would be nice... I would have to generate a table for each document type, for each job... unless anyone sees anything I do not? I am pretty new at this, so any help would be appreciated.
Here is what I have for my procedure that I am having issues with.
DELIMITER $$
DROP PROCEDURE IF EXISTS ADD_NEW_DOC$$
CREATE DEFINER=RMDNA#localhost PROCEDURE ADD_NEW_DOC(IN in_job INT, IN in_type VARCHAR(2), IN in_name VARCHAR(32), IN in_desc VARCHAR(512))
BEGIN
SELECT MAX(doc_id) INTO #highnum FROM Doc_Entries WHERE job_id = in_job AND doc_type_ID = in_type$$
IF #highnum = null THEN SET #newnum = 1$$
ELSE SET #newnum = #highnum + 1$$
END IF$$
insert into Doc_Entries (job_id, doc_type_ID, doc_id, doc_name, doc_desc) values (in_job, in_type, #newnum, in_name, in_desc)$$
SELECT #newnum$$
END$$
DELIMITER ;
and the error I am getting is:
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 2
UPDATE:
My attempt has refined...
DROP PROCEDURE IF EXISTS ADD_NEW_DOC;
DELIMITER //
CREATE DEFINER=RMDNA#localhost PROCEDURE ADD_NEW_DOC(IN in_job INT, IN in_type VARCHAR(2), IN in_name VARCHAR(32), IN in_desc VARCHAR(512))
BEGIN
SELECT MAX(doc_id) INTO #highnum FROM Doc_Entries WHERE job_id = in_job AND doc_type_ID = in_type;
IF (#highnum is null) THEN SET #newnum = 1;
ELSE SET #newnum = #highnum + 1;
END IF;
insert into Doc_Entries (job_id, doc_type_ID, doc_id, doc_name, doc_desc) values (in_job, in_type, #newnum, in_name, in_desc);
SELECT #newnum;
END//
DELIMITER ;
Working good now. Learned how to use delimiter properly and fixed a few things that then became obvious.

want to apply transaction on below procedure but its not working

DELIMITER $$
USE `g4winners2`$$
DROP PROCEDURE IF EXISTS `ebetToTbConsumer`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ebetToTbConsumer`()
BEGIN
START TRANSACTION;
INSERT INTO g4winners2.`tb_consumer`(first_name,middle_name,last_name,username,PASSWORD ,ssn,email,home_phone
,date_of_birth,gender_type,is_locked,is_active,is_online,bonus_level_id,modified_by_entity,modified_by_id,record_created_on,record_modified_on
,consumer_status_type
,business_id,driver_license,driver_license_state_provice,mothers_maiden_name,id_type,intl_id_state_code,id_expiration,id_status,COMMENT,reward_profile_id
,player_tracking_id
)
SELECT cont.first_name, cont.middle_initial, cont.last_name,cust.user_name, cust.encrypted_password, cust.social_security_number, cont.email,cont.home_phone,cust.birthdate,
cust.sex,
b'0',b'1',b'0',1,'3',1, FROM_UNIXTIME(cust.signup_date), FROM_UNIXTIME(cust.updated_date) ,cust.status,cust.business_id,cust.drivers_license,cust.drivers_license_state_province,cust.mothers_maiden_name,cust.id_type,cust.intl_id_state_code,
cust.id_expiration,cust.id_status,cust.comment,cust.reward_profile_id,cust.player_tracking_id
FROM ebet.`contact_info` cont ,ebet.`customer` cust WHERE cust.id=cont.customer_id ;
INSERT INTO `g4winners2`.`tb_consumer_address`(consumer_id,address_line_1,address_line_2
,city,state,zip_code,country,county,region,record_modified_on,mailing_list_flag,
funding_notification_flag,title,marketing1,partner_list_flag,company_name)
SELECT cont.customer_id, cont.address1,cont.address2,cont.city,cont.state_province,cont.postal_code,cont.country,cont.county,cont.suburb ,cont.updated_date, cont.mailing_list_flag,
cont.funding_notification_flag,cont.title,cont.marketing1,cont.partner_list_flag,cont.company_name FROM ebet.`contact_info` cont;
INSERT INTO g4winners2.tb_consumer_funds(tote_account_id,pin,total_available_fund,onhold_fund,tote_account_status,last_access)
SELECT acc.acct_number,acc.encrypted_pin, FLOOR(acc.current_balance),FLOOR(acc.hold_balance), acc.status,acc.last_access
FROM ebet.`account` acc;
INSERT INTO g4winners2.`tb_system_settings`(setting_id,setting_name,setting_value,business_id )
SELECT 0,conf.name,conf.value,conf.business_id FROM ebet.`config1` conf;
COMMIT;
END$$
DELIMITER ;
After creating the procedure, you need to run it. Have you tried to run it using
CALL ebetToTbConsumer(); ?
Your table g4winners2.tb_consumer contains some fields named with reserved words. PASSWORD, and COMMENT MUST be escaped when when using them in your table or you avoid them completely.
Also for g4winners2.tb_system_settings.setting_id field, make sure of the inserted value 0, if it would not throw some constraint error. You're better off if you take a look at the MySQL error log to really see what's going wrong.
You have to set the Server variable autocommit to OFF. You can set it globally bu adding it to server configuration file or explicitly set in procedure as below:
DELIMITER $$
USE `g4winners2`$$
DROP PROCEDURE IF EXISTS `ebetToTbConsumer`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ebetToTbConsumer`()
BEGIN
SET autocommit=0; /******************Check this line******************/
START TRANSACTION;
INSERT INTO g4winners2.`tb_consumer`(first_name,middle_name,last_name,username,PASSWORD ,ssn,email,home_phone
,date_of_birth,gender_type,is_locked,is_active,is_online,bonus_level_id,modified_by_entity,modified_by_id,record_created_on,record_modified_on
,consumer_status_type
,business_id,driver_license,driver_license_state_provice,mothers_maiden_name,id_type,intl_id_state_code,id_expiration,id_status,COMMENT,reward_profile_id
,player_tracking_id
)
SELECT cont.first_name, cont.middle_initial, cont.last_name,cust.user_name, cust.encrypted_password, cust.social_security_number, cont.email,cont.home_phone,cust.birthdate,
cust.sex,
b'0',b'1',b'0',1,'3',1, FROM_UNIXTIME(cust.signup_date), FROM_UNIXTIME(cust.updated_date) ,cust.status,cust.business_id,cust.drivers_license,cust.drivers_license_state_province,cust.mothers_maiden_name,cust.id_type,cust.intl_id_state_code,
cust.id_expiration,cust.id_status,cust.comment,cust.reward_profile_id,cust.player_tracking_id
FROM ebet.`contact_info` cont ,ebet.`customer` cust WHERE cust.id=cont.customer_id ;
INSERT INTO `g4winners2`.`tb_consumer_address`(consumer_id,address_line_1,address_line_2
,city,state,zip_code,country,county,region,record_modified_on,mailing_list_flag,
funding_notification_flag,title,marketing1,partner_list_flag,company_name)
SELECT cont.customer_id, cont.address1,cont.address2,cont.city,cont.state_province,cont.postal_code,cont.country,cont.county,cont.suburb ,cont.updated_date, cont.mailing_list_flag,
cont.funding_notification_flag,cont.title,cont.marketing1,cont.partner_list_flag,cont.company_name FROM ebet.`contact_info` cont;
INSERT INTO g4winners2.tb_consumer_funds(tote_account_id,pin,total_available_fund,onhold_fund,tote_account_status,last_access)
SELECT acc.acct_number,acc.encrypted_pin, FLOOR(acc.current_balance),FLOOR(acc.hold_balance), acc.status,acc.last_access
FROM ebet.`account` acc;
INSERT INTO g4winners2.`tb_system_settings`(setting_id,setting_name,setting_value,business_id )
SELECT 0,conf.name,conf.value,conf.business_id FROM ebet.`config1` conf;
COMMIT;
END$$
DELIMITER ;

MySQL - Stored Proc creation in code giving syntax error

I'm baffled by the syntax error I keep getting in MYSQL (ver 5.2) when executing CREATE PROC in code.
The MySQL Proc code:
DELIMITER //
CREATE PROCEDURE Delete_BillOfMaterialsDetail
(IN InOrderDate DATE,
IN InProductCode varchar(40),
IN InRawMaterialProductCode varchar(40)
)
BEGIN
IF EXISTS
(SELECT * FROM basf_rawmaterialplanning.BillOfMaterialsDetail
WHERE OrderDate = InOrderDate
and ProductCode = InProductCode
and RawMaterialProductCode = InRawMaterialProductCode)
THEN
DELETE FROM basf_rawmaterialplanning.BillOfMaterialsDetail
WHERE OrderDate = InOrderDate
AND ProductCode = InProductCode
AND RawMaterialProductCode = InRawMaterialProductCode;
END IF;
END //
DELIMITER ;
I build it using a string datatype then execute it against the DB which gives a syntax error.
I'm not to sure what I'm doing wrong?
Thanks Guys i figured it out, will post the answer as so as StackOverflow allows me to
Just execute the command for changing delimiter separately and then execute the stored procedure create command.
The system is currently considering it to be one single command and hence the error :)
Try this code -
CREATE PROCEDURE Delete_BillOfMaterialsDetail3(
IN InOrderDate DATE,
IN InProductCode varchar(40),
IN InRawMaterialProductCode varchar(40))
DELETE FROM basf_rawmaterialplanning.BillOfMaterialsDetail
WHERE OrderDate = InOrderDate
AND ProductCode = InProductCode
AND RawMaterialProductCode = InRawMaterialProductCode;
Thanks Guys, finally figured it out
I added my script in the MySqlScript object and executed using that class, works 100% without any syntax errors