Error Code: 1064 in mysql - mysql

I created a procedure that is supposed to do some operation but every time I call it, mysql comes out with an error, which I have not clue what it means. I have tried to understand it in vain, here 's the table structure which the stored procedure where made to do an operation on it:
CREATE TABLE `recruitment`.`job_seeker` (
`user_id` INT Null ,
`fname` VARCHAR(45) Null ,
`lname` VARCHAR(45) Null ,
`mname` VARCHAR(45) Null ,
`gender` VARCHAR(10) Null ,
`dob` DATE Null ,
`marital_status` VARCHAR(45) Null ,
`address` VARCHAR(45) Null ,
`city` VARCHAR(45) Null ,
`nationality` VARCHAR(45) Null ,
`phone` VARCHAR(45) Null ,
`mobile` VARCHAR(45) Null ,
`degree_id` INT Null ,
`education` VARCHAR(100) Null ,
`experience` VARCHAR(250) Null ,
`other` VARCHAR(250) Null ,
`job_target` VARCHAR(250) Null ,
PRIMARY KEY (`user_id`) ,
INDEX `user_id` (`user_id` ASC) ,
INDEX `degree_id` (`degree_id` ASC) ,
CONSTRAINT `user_id`
FOREIGN KEY (`user_id` )
REFERENCES `recruitment`.`user_authentication` (`user_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `degree_id`
FOREIGN KEY (`degree_id` )
REFERENCES `recruitment`.`degree` (`degree_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
Here's the stored procedure:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `createSeekerProfile`(in userName varchar(45),
in fn varchar(45),in mn varchar(45), in ln varchar(45),
in gender varchar(6),in nationality varchar(45),
in ad varchar(45),in city varchar(45),in phone varchar(15),in mob varchar(15),
in maritalStatus varchar(45), in degId int, in educ varchar(100),
in exper varchar(250), in other varchar(250),
in dob date,in jtarg varchar(250))
begin
declare returned_ID int;
set #dyn_que = CONCAT('select user_id into #returned_ID
from user_authentication where user_name = ? ');
prepare s1 from #dyn_que ;
set #usn = userName;
execute s1 using #usn ;
set #dyn_update =CONCAT('update job_seeker set fname =',fn,', lname = ',ln,' ,mname = ',mn,' ,
nationality =',nationality,',address =',ad,',city =',city,',phone=',phone,',
mobile =',mob,', gender = ',gender,',other =',other,',
degree_id =',degId,', job_target=',jtarg,', dob =',dob,', education =',educ,',
experience=',exper,', marital_status=',maritalStatus,' where user_id =#returned_ID');
prepare s2 from #dyn_update;
execute s2;
end
Whenever I call the procedure through:
call createSeekerProfile('realsilhouette','robert','marie','david','male'
,'earthal','an address here','capital of earth','012178152',
'1111111111','single',2,'engineering','looking forward','determined',
'2008-7-04','Oracle CEO')
I get an awful error which is:
Error Code: 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 'address here,
city =capital of earth,phone=012178152,
mobile =1111111111, gender' at line 2
However when I try execute the update statement manually which is inside stored procedure, it works out so well.
new Post :
thanks god,finally I fixed the problem up, The problem came down to the order, all I did was just make the parameters in order, though update statement does not care about the order, as far as I know, I'm not sure, But what i am sure of is the stored procedure got created beautifully, here's the new code :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `createSeekerProfile`(
in un varchar(45),
in fn varchar(45),
in ln varchar(45),
in mn varchar(45),
in g varchar(10),
in dateOfBirth date,
in ms varchar(45),
in ad varchar(45),
in city varchar(45),
in nat varchar(45),
in ph varchar(45),
in mob varchar(45),
in degid int,
in educ varchar(100),
in exp varchar(250),
in other varchar(250),
in jtarg varchar(250))
begin
declare returned_ID int(11);
set #dyn_que = CONCAT('select user_id into #returned_ID from user_authentication
where user_name = ? ');
prepare s1 from #dyn_que ;
set #usn = un;
execute s1 using #usn ;
set #dyn_update =CONCAT('update job_seeker set fname
="',fn,'",lname="',ln,'",mname="',mn,'",lname ="',ln,'",
gender ="',g,'",dob="',dateOfBirth,'",marital_status="',ms,'",
address="',ad,'",city="',city,'",
nationality="',nat,'",phone="',ph,'",mobile="',mob,'",degree_id="',
degid,'",education="',educ,'",
experience="',exp,'",other="',other,'",job_target="',jtarg,'"
where user_id = #returned_ID');
prepare stm from #dyn_update;
execute stm;
end $$
many thanks

Your forgot about quoting string values.
for example:
concat('update yourTable
set address ="', #address, '"
where id = 1');
or use function quote

For me adding character ` (GRAVE ACCENT) helped. It is not a single quote (')

CREATE TABLE Order
(
Order_Id integer NOT NULL ,
Order_Time datetime NULL ,
Order_Status char(50) NULL ,
Customer_Id integer NOT NULL
)

Related

Create stored procedure with updating multiple columns

I am getting the following error in my code:
MySQL said: Documentation
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 'END' at line 20
CREATE PROCEDURE updateUser(
IN firstname VARCHAR(20),
IN Vlastname VARCHAR(20),
IN Vemail VARCHAR(50),
IN Vpassword VARCHAR(100),
IN Vyear INT(5),
IN Vgender VARCHAR(10),
IN Vprefer VARCHAR(200),
IN Vinterested VARCHAR(200),
IN Vabout VARCHAR(200),
IN Vid INT(11)
)
BEGIN
UPDATE users SET
name = (CASE WHEN firstname IS NOT NULL THEN firstname ELSE name
END),
lastname = (CASE WHEN vlastname IS NOT NULL THEN vlastname ELSE lastname
END)
WHERE id = Vid
END;
When developing stored procedures in MySQL, you must set a delimiter different from ; to properly end the stored program statement. This allows the use of ; to delineate multiple statements within the procedure.
Per MySQL 25.1 Defining Stored Programs docs:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
Therefore consider below adjustment:
DELIMITER // -- TEMPORARILY CHANGE DELIMITER FROM ;
CREATE PROCEDURE updateUser (
IN firstname VARCHAR(20),
IN Vlastname VARCHAR(20),
IN Vemail VARCHAR(50),
IN Vpassword VARCHAR(100),
IN Vyear INT(5),
IN Vgender VARCHAR(10),
IN Vprefer VARCHAR(200),
IN Vinterested VARCHAR(200),
IN Vabout VARCHAR(200),
IN Vid INT(11)
)
BEGIN
UPDATE `users`
SET
`name` = CASE WHEN `firstname` IS NOT NULL THEN `firstname` ELSE `name` END,
`lastname` = CASE WHEN `vlastname` IS NOT NULL THEN `vlastname` ELSE `lastname` END
WHERE `id` = Vid; -- SEMICOLON HERE TO SEPARATE STATEMENTS
END
// -- PROPERLY END PROCEDURE STATEMENT
DELIMITER ; -- RESET DELIMITER BACK TO ;
you are missing a semicolon after The WHERE clause
And you can simplify it
DELIMITER //
CREATE PROCEDURE updateUser(
IN firstname VARCHAR(20),
IN Vlastname VARCHAR(20),
IN Vemail VARCHAR(50),
IN Vpassword VARCHAR(100),
IN Vyear INT(5),
IN Vgender VARCHAR(10),
IN Vprefer VARCHAR(200),
IN Vinterested VARCHAR(200),
IN Vabout VARCHAR(200),
IN Vid INT(11)
)
BEGIN
UPDATE users SET
name = COALESCE (firstname, name),
lastname = COALESCE (vlastname,lastname)
WHERE id = Vid;
END//
DELIMITER ;

When I'm trying to update a record I get error #1062 - Duplicate entry for key 'ID_UNIQUE'

I'm using the following stored-procedure to update a table:
DELIMITER $$
CREATE DEFINER=`developer`#`localhost` PROCEDURE `update_patient`(IN `patient_id` INT(11), IN `name` VARCHAR(45), IN `surname` VARCHAR(45), IN `middle_name` VARCHAR(45), IN `email` VARCHAR(45), IN `phone` VARCHAR(45), IN `mobile` VARCHAR(45), IN `address_id` INT(11), IN `address_no` VARCHAR(8), IN `ID` VARCHAR(45), IN `DOB` DATE)
NO SQL
UPDATE
patient
SET name = name,
surname = surname,
middle_name = middle_name,
email = email,
phone = phone,
mobile = mobile,
address_id = address_id,
address_no = address_no,
ID = ID,
DOB = DOB
WHERE
patient_id = patient_id
LIMIT 1;
END$$
DELIMITER ;
When I'm trying to call it through phpmyadmin I get the error: #1062 - Duplicate entry '844844' for key 'ID_UNIQUE'
844844 refers to ID field. I have this field in patient table and I want to update the patient's data. However, the primary key of patient table is patiend_id and not ID.
Do you know how to fix the error?
The problem is your input params for the Stored procedure are same as your column names in the table. This is leading to ambiguous behaviour.
Eg: In SET name = name ; how does MySQL resolve which one of this is the param value and which one is the column name ?
I generally prefix IN params with in_ and OUT with out_ for code readability and avoiding ambiguous behaviour.
DELIMITER $$
CREATE definer=`developer`#`localhost`
PROCEDURE `update_patient`(IN `in_patient_id` INT(11),
IN `in_name` VARCHAR(45),
IN `in_surname` VARCHAR(45),
IN `in_middle_name` VARCHAR(45),
IN `in_email` VARCHAR(45),
IN `in_phone` VARCHAR(45),
IN `in_mobile` VARCHAR(45),
IN `in_address_id` INT(11),
IN `in_address_no` VARCHAR(8),
IN `in_id` VARCHAR(45),
IN `in_dob` date)
NO SQL
UPDATE patient
SET name = in_name,
surname = in_surname,
middle_name = in_middle_name,
email = in_email,
phone = in_phone,
mobile = in_mobile,
address_id = in_address_id,
address_no = in_address_no,
id = in_id,
dob = in_dob
WHERE patient_id = in_patient_id
LIMIT 1;
END$$
DELIMITER ;

Stored procedure not working as expected

Am trying to create a stored procedure that will notify me if a username or email already exists in the table.
Here is the structure of my table
CREATE TABLE IF NOT EXISTS `user` (
`user_id` smallint(5) unsigned NOT NULL,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`email` varchar(60) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(128) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`date_joined` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_category_id` tinyint(3) unsigned NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
and here is the code for the stored procedure
DELIMITER $$
CREATE PROCEDURE `sp_create_account`( username_param VARCHAR(40), email_param VARCHAR(60), pass VARCHAR(30), category_id TINYINT )
BEGIN
DECLARE salt VARCHAR(60);
DECLARE username_var VARCHAR(40);
DECLARE email_var VARCHAR(60);
SELECT username_var INTO username_var FROM user WHERE username = username_param;
SELECT email_var INTO email_var FROM user WHERE email = email_param;
IF username_var = username_param THEN
SELECT 'username' AS message;
ELSEIF email_var = email_param THEN
SELECT 'email' AS message;
ELSE
SET salt = '#4$^7EC%?';
SET salt = CONCAT( username_param, salt );
INSERT INTO user VALUES
( DEFAULT, username_param, email_param, AES_ENCRYPT( pass, salt ), DEFAULT, DEFAULT, category_id );
SELECT 'created' AS message;
END IF;
END$$
DELIMITER ;
Two problems:
Problem 1:
Everything works fine when inserting an unique entry in which has the username or email does not exist, but when the username or email does exist i get these errors in the screenshot below yet i expect the stored procedure to return a simple select indicating where the problem could be or indicated success as the in case when it returns 'created'
Problem 2
If it is a unique entry and it gets inserted into the table, the password column cell in that particular row gets inserted with an empty string.
What could be the cause of all the above? Thanks you.
Perhaps these changes are what you are looking for. Changes to the schema, and your if blocks, and return values.
The return value is the AUTO_INCREMENT of the user id. Note, I pretty much followed your schema. Your Primary Key in that table could probably be collapsed a bit. Some might go lean with no user id or user name, but just the email address as the PK. Those are things to think about. I also added a unique key for email address.
Schema:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int auto_increment primary key,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`email` varchar(60) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varbinary(128) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
`date_joined` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_category_id` tinyint(3) unsigned NOT NULL,
unique key (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- truncate table user;
Stored Procedure:
drop procedure if exists sp_create_account;
DELIMITER $$
CREATE PROCEDURE `sp_create_account`
( username_param VARCHAR(40),
email_param VARCHAR(60),
pass VARCHAR(30),
category_id TINYINT
)
BEGIN
DECLARE salt VARCHAR(60);
DECLARE username_var VARCHAR(40);
DECLARE email_var VARCHAR(60);
DECLARE recFound int;
DECLARE foundStatus int DEFAULT 0;
SELECT user_id INTO recFound FROM user WHERE username = username_param;
IF recFound is null THEN
SELECT user_id INTO recFound FROM user WHERE email = email_param;
IF recFound is not null THEN
SET foundStatus=1;
END IF;
ELSE
SET foundStatus=1;
END IF;
IF foundStatus=0 THEN
SET salt = '#4$^7EC%?';
SET salt = CONCAT( username_param, salt );
INSERT INTO user (username,email,password,active,date_joined,user_category_id) VALUES
( username_param, email_param, AES_ENCRYPT( pass, salt ), DEFAULT, DEFAULT, category_id );
set recFound=LAST_INSERT_ID();
END IF;
SELECT recFound;
END$$
DELIMITER ;
Test:
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('Katherine','ksmith#hotmail.com','thepass01',101);
call sp_create_account('caspar','caspar001#gmail.com','thepass02',77);
select * from user;
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
| user_id | username | email | password | active | date_joined | user_category_id |
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
| 1 | Katherine | ksmith#hotmail.com | _╦*Fó▄GàB╔┌O►²§' | 1 | 2016-07-13 17:56:54 | 101 |
| 2 | caspar | caspar001#gmail.com | ♀½B§5U├↨I♀#*├ ∟L | 1 | 2016-07-13 17:57:09 | 77 |
+---------+-----------+---------------------+------------------+--------+---------------------+------------------+
2 rows in set (0.00 sec)
Your last ELSE needs to have all the commands you expect to execute in it enclosed in BEGIN ... END. Maybe? I've been working more in MSSQL lately.

failed to change '' to null for datetime in mysql stored procedure

i wrote the stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `SP_create_new_task`(
IN _taskName VARCHAR(30),
IN _description VARCHAR(500),
IN _startDate DATETIME,
IN _endDate DATETIME,
IN _lacation VARCHAR(30),
IN _subTo INT
)
BEGIN
INSERT INTO tm_tasks (taskName, description, startDate, endDate, lacation, subTo)
VALUES (_taskName, _description, NULLIF(_startDate,''), NULLIF(_endDate,''), _lacation, _subTo);
END
I run it:
call task_tool.SP_create_new_task('name1 ', 'description1', '', '', 'lacation1', 1);
and got this error:
Error Code: 1292. Incorrect datetime value: '' for column '_startDate' at row 1
why NULLIF() didn't enter Null value to _startDate???
for your convenience, task table query:
CREATE TABLE tm_tasks(
ID INT PRIMARY KEY AUTO_INCREMENT,
taskName VARCHAR(30) NOT NULL,
description VARCHAR(500),
joinDate TIMESTAMP,
startDate DATETIME NULL DEFAULT NULL,
endDate DATETIME NULL DEFAULT NULL,
lacation VARCHAR(30),
subTo INT DEFAULT NULL,
ignoreRow TINYINT(1) DEFAULT 0
);
Thanks!
You get this error because it doesn't even get to insert.
Error Code: 1292. Incorrect datetime value: '' for column '_startDate'
at row 1
It fails here:
CREATE DEFINER=`root`#`localhost` PROCEDURE `SP_create_new_task`(
IN _taskName VARCHAR(30),
IN _description VARCHAR(500),
**IN _startDate DATETIME**,
When you try to pass '' to DATETIME parameter.
What you trying to do:
'' -> _startDate DATETIME parameter -> INSERT -> NULLIF(_startDate, '') -> NULL
should be:
NULL -> _startDate DATETIME parameter -> INSERT -> NULL
Pass NULL directly and don't do workaround with NULLIF().
CALL task_tool.SP_create_new_task('name1 ', 'description1', NULL, NULL, 'lacation1', 1);

MySQL stored procedure anomaly: One line gets executed, another skipped?

I have a stored procedure, that checks if there is a user with the same e-mail address as the input, if not, then registeres one.
Here is the table:
CREATE TABLE IF NOT EXISTS `overkill`.`accounts` (
`accountID` INT NOT NULL AUTO_INCREMENT ,
`email` VARCHAR(64) NOT NULL ,
`firstName` VARCHAR(32) NOT NULL ,
`lastName` VARCHAR(32) NOT NULL ,
`passSaltedSHA` BINARY(20) NOT NULL ,
`salt` BINARY(20) NOT NULL ,
`gender` ENUM('m','f') NOT NULL ,
`birthDate` DATE NOT NULL ,
`regTime` TIMESTAMP NOT NULL ,
PRIMARY KEY (`accountID`) )
ENGINE = InnoDB;
Here is the stored procedure:
DELIMITER $$
CREATE PROCEDURE `overkill`.`registerUser` (
IN emailIN VARCHAR(64),
IN passwordIN VARCHAR(16),
IN firstNameIN VARCHAR(32),
IN lastNameIn VARCHAR(32),
IN birthIN DATE,
IN genderIN ENUM('f','m'))
BEGIN
DECLARE existingMailAccLOG INT DEFAULT NULL;
DECLARE saltLOC CHAR(40);
DECLARE regSuccessLOC BOOLEAN DEFAULT FALSE;
SELECT COUNT(*) INTO existingMailAccLOG FROM `overkill`.`accounts` WHERE `accounts`.`email` = emailIN;
IF existingMailAccLOG = 0 THEN
SET saltLOC = SHA1(rand());
SET regSuccessLOC = TRUE;
INSERT INTO `overkill`.`accounts` (`email`, `firstName`, `lastName`, `passSaltedSHA`, `salt`, `gender`, `birthDate`) VALUES(emailIN, firstNameIN, lastNameIn, UNHEX(SHA1(CONCAT(passwordIN, saltLOC))), UNHEX(saltLOC), genderIN, birthIN);
END IF;
SELECT regSuccessLOC AS `registered`, saltLOC AS `salt`;
END
If I call:
CALL registerUser("abc#def.com", "pass", "firstn", "lastn", "2012-01-01", "f");
It inserts a line into the accounts table, but forgets to return the proper values that I set inside the IF
SET saltLOC = SHA1(rand());
SET regSuccessLOC = TRUE;
How is it even possible? Why are theese lines skipped and INSERT still gets executed, without mistake?
Try to add "#" in front of your variable names after DECLARE keyword. It can cause some confusion, as it is described here: MySQL: #variable vs. variable. Whats the difference? (Part2) and here: MySQL: #variable vs. variable. Whats the difference?