Stored procedure not working for inserting data - mysql

I have this table:
User
user_id int PK
username varchar(20)
secret_code varchar(20)
name varchar(20)
age int
gender varchar(20)
city varchar(20)
latest_signin_time timestamp
latest_signout_time timestamp
loc_list json
buddy_list json
I created a stored procedure:
create procedure insert_users(IN user_id int , in username varchar(20),in secret_code varchar(20),
in name varchar(20), in age int, in gender varchar(20), in city varchar(20),
in latest_signin_time timestamp, in latest_signout_time timestamp,
in loc_list json , in buddy_list json)
begin
insert into user values(user_id, username, secret_code, name, age, gender, city,
latest_signin_time, latest_signout_time, loc_list,buddy_list)
end ;
call insert_user(​'1', 'avs431','pwd1','Ameya','22','Male','Mumbai',null,null,'[]','[]'​​);
However, my code isn't running and I keep getting "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 'end' at line 9"
I'm not sure what is going wrong here. Can anyone help?
Thank you!

create procedure insert_users(IN user_id int , in username varchar(20),in secret_code varchar(20),
in name varchar(20), in age int, in gender varchar(20), in city varchar(20),
in latest_signin_time timestamp, in latest_signout_time timestamp,
in loc_list json , in buddy_list json)
/* begin */
insert into user values(user_id, username, secret_code, name, age, gender, city,
latest_signin_time, latest_signout_time, loc_list,buddy_list)
/* end */ ;

The commands in procedure terminate with semicolon (;). Use prefixes in the procedure parameters so the parameters won't be mixed up with column names. Also, list the column names in INSERT so your procedure will work even if a column is added to the table.
delimiter //
create procedure insert_users(
in_user_id int,
in_username varchar(20),
in_secret_code varchar(20),
in_name varchar(20),
in_age int,
in_gender varchar(20),
in_city varchar(20),
in_latest_signin_time timestamp,
in_latest_signout_time timestamp,
in_loc_list json,
in_buddy_list json
)
begin
insert into user (user_id, username, secret_code, name, age, gender,
city, latest_signtime, latest_signout_time, loc_list, buddy_list)
values(in_user_id, in_username, in_secret_code, in_name, in_age, in_gender,
in_city, in_latest_signin_time, in_latest_signout_time, in_loc_list, in_buddy_list);
end
//
delimiter ;
call insert_user(​'1', 'avs431','pwd1','Ameya','22','Male','Mumbai',null,null,'[]','[]'​​);

Related

How to pass string variable inside stored procedure in MySQL

Hi I am working on stored procedure. In this stored procedure I am inserting data in one table. But in that insert statement I am also using select statement just to get id of another table just for optimization purpose. But in that select statement I am passing string variable for comparison and I am getting following error
Error: ER_CANT_AGGREGATE_2COLLATIONS: Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8mb4_0900_ai_ci,IMPLICIT) for operation '='
My table structure where I am inserting data is as follows:
table name : user_data
Columns:
user_data_id : INT PK
user_id: INT
country_id : INT
state_id : INT
city_id: INT
created_date: DATETIME
Also table structure of country, state and city master tables are as follows:
table name : country_master
columns:
country_master_id : INT PK
name: VARCHAR(100)
table name : state_master
columns:
state_master_id : INT PK
name: VARCHAR(100)
table name : city_master
columns:
city_master_id : INT PK
name: VARCHAR(100)
My stored procedure which is having issue is as follows:
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_saveData`(IN userId INT, IN countryName VARCHAR(100), IN stateName VARCHAR(100), IN cityName VARCHAR(100), IN createdDate DATETIME)
BEGIN
INSERT INTO user_data(user_id, country_id, state_id, city_id, created_date)
VALUES (
userId,
(SELECT mst_country_id FROM mst_country WHERE name=countryName),
(SELECT mst_state_id FROM mst_state WHERE name=stateName),
(SELECT mst_city_id FROM mst_city WHERE name=cityName),
createdDate)
;
END
I have tried using following way.
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_saveData`(IN userId INT, IN countryName VARCHAR(100), IN stateName VARCHAR(100), IN cityName VARCHAR(100), IN createdDate DATETIME)
BEGIN
INSERT INTO user_data(user_id, country_id, state_id, city_id, created_date)
VALUES (
userId,
(SELECT mst_country_id FROM mst_country WHERE name=#countryName),
(SELECT mst_state_id FROM mst_state WHERE name=#stateName),
(SELECT mst_city_id FROM mst_city WHERE name=#cityName),
createdDate)
;
END
In this case I am not getting above error but its inserting null values in country_id, city_id and state_id columns.
Please help me in this. I am stuck here.
Thanks in advance
Over-normalization. There is essentially no advantage and some potential disadvantages to normalizing city, state, and country.
I do suggest using the 2-byte standard
country_code CHAR(2) CHARACTER SET ascii
for countries.

I don't know what's wrong with my MYSQL procedure

to try to create a procedure in MYSQL workbench but I'm not succeeding ..
A procedure inserts into a table with parameters coming from an ASP program, inserts into the campaign table, then by the inserted ID, inserts into another table and returns the inserted id from that table in the last table.
What am I doing wrong? I'm getting used to SQL Server....
CREATE PROCEDURE Insert_Campaign_Indicator(
IN Name VARCHAR(50),
IN Email VARCHAR(50),
IN Phone VARCHAR(50),
IN Active INT,
IN Type INT,
IN UserId INT,
IN CampaignId INT
)
BEGIN
INSERT INTO Indicator(Name, Email, Phone, Link, Active, CleaningType, Type, UserId)
VALUES (Name, Email, Phone, uuid(), Active, 2, Type, UserId);
INSERT INTO CampaignIndicator (CampaignId, IndicatorId, Link, ResearchWasSent, ReadyToRefer, AcceptedRefer, Active, UserId)
VALUES (CampaignId, LAST_INSERT_ID(), uuid(),0,0,0, 1, UserId);
SELECT Link FROM CampaignIndicator WHERE Id = LAST_INSERT_ID();
END //
DELIMITER ;
Never use Column names as variable, MySQL gets confused
The code is without DELIMITER because of the dbfddle site you have to add them
CREATE TABLE Indicator(id int AUTO_INCREMENT PRIMARY KEY,Name VARCHAR(50)
, Email VARCHAR(50), Phone VARCHAR(50), Link VARCHAR(36),Active Int, CleaningType int, Type int, UserId int)
CREATE TABLE CampaignIndicator (id int AUTO_INCREMENT PRIMARY KEY,CampaignId int
, IndicatorId int, Link VARCHAR(36), ResearchWasSent int, ReadyToRefer int, AcceptedRefer int
, Active int, UserId int)
CREATE PROCEDURE Insert_Campaign_Indicator(
IN _Name VARCHAR(50),
IN _Email VARCHAR(50),
IN _Phone VARCHAR(50),
IN _Active INT,
IN _Type INT,
IN _UserId INT,
IN _CampaignId INT
)
BEGIN
INSERT INTO Indicator(Name, Email, Phone, Link, Active, CleaningType, Type, UserId)
VALUES (_Name, _Email, _Phone, uuid(), _Active, 2, _Type, _UserId);
INSERT INTO CampaignIndicator (CampaignId, IndicatorId, Link, ResearchWasSent, ReadyToRefer, AcceptedRefer, Active, UserId)
VALUES (_CampaignId, LAST_INSERT_ID(), uuid(),0,0,0, 1, _UserId);
SELECT Link FROM CampaignIndicator WHERE Id = LAST_INSERT_ID();
END
CALL Insert_Campaign_Indicator('A','B','C',1,1,1,1)
| Link |
| :----------------------------------- |
| 28aee8e1-d169-11eb-96e0-00163e64f9cc |
✓
db<>fiddle here

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 ;

Couldn't get the call addusers procedure to work for testing because of auto increment

I have problem with Addusers procedure because I add UserID as out for auto increment since I basically want to pass:
CALL addusers
(
'Rory',
'Covertry',
'5566',
'rory#gmail.com'
'1234',
'U'
)
I'm expected to insert the data but I ended getting an error like this.
"Error
SQL query:
CALL addusers
(
'Rory',
'Covertry',
'5566',
'rory#gmail.com'
'1234',
'U'
)
MySQL said: Documentation
1318 - Incorrect number of arguments for PROCEDURE construction.addusers; expected 7, got 5"
Here's my stored procedure for
addusers
DELIMITER go
Create procedure Addusers(
Out UserID int(11),
IN FirstName varchar(30),
IN LastName varchar(30),
IN Password varchar(30),
IN EmailAddress varchar(30),
IN Salt varchar(40),
IN RoleID varchar(1))
BEGIN
insert into users(
FirstName,
LastName ,
Password ,
EmailAddress ,
Salt ,
RoleID
)
Values
(
FirstName,
LastName ,
Password ,
EmailAddress ,
Salt ,
RoleID
);
set UserID = AUTO_INCREMENT;
End
go
DELIMITER ;
You must use last_insert_id() instead of AUTO_INCREMENT reserved word, and put all 7 parameters when you do a call:
DELIMITER go
Create procedure Addusers(
Out UserID int(11),
IN FirstName varchar(30),
IN LastName varchar(30),
IN Password varchar(30),
IN EmailAddress varchar(30),
IN Salt varchar(40),
IN RoleID varchar(1))
BEGIN
insert into users(
FirstName,
LastName ,
Password ,
EmailAddress ,
Salt ,
RoleID
)
Values
(
FirstName,
LastName ,
Password ,
EmailAddress ,
Salt ,
RoleID
);
set UserID = last_insert_id();
End
go
DELIMITER ;
To get the OUT parameter you must use a session variable like this:
set #new_id = null;
call addusers(#new_id,'Rory','Covertry','5566','rory#gmail.com','1234','U' );
select #new_id; -- contains the inserted id

how to create insert stored procedure mysql

I am trying to create a stored procedure and i am getting an error code.
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 '' at line 12
I'm not the greatest with MYSQL and I'm unsure where to even look to figure the problem out.
Create Procedure Sp_insertCustomer(
IN Customer_id VARCHAR(20) ,
IN UserName VARCHAR(20),
IN Fname VARCHAR(20),
IN Lname VARCHAR(20),
IN Dob Date,
IN Address VARCHAR(250),
IN Phone INT,
IN Email VARCHAR(250),
IN Ss VARCHAR(9) )
BEGIN
INSERT INTO Customer (Cusomter_id,UserName,Fname,Lname,Dob,Address,Phone,Email,Ss)
VALUES (in_Customer_id ,in_UserName , in_Fname , in_Lname , in_Dob , in_Address , in_Phone , in_Email , in_Ss);
END
1) Your parameters and values in insert statement are different:
Customer_id is parameter and in_Customer_id in insert statement
2) add delimeters
DELIMITER $$
< your procedure >
END$$ --- instead your END
DELIMITER ;
It seems like you missed the parameters names. Also you are not need to specify IN for params.
DELIMITER $$
Create Procedure Sp_insertCustomer(
Customer_id VARCHAR(20) ,
UserName VARCHAR(20),
Fname VARCHAR(20),
Lname VARCHAR(20),
Dob Date,
Address VARCHAR(250),
Phone INT,
Email VARCHAR(250),
Ss VARCHAR(9) )
BEGIN
INSERT INTO Customer (Cusomter_id, UserName, Fname, Lname, Dob, Address, Phone, Email, Ss)
VALUES (Customer_id, UserName, Fname, Lname, Dob, Address, Phone, Email, Ss);
END$$