MySql Stored Procedure : Get Last Inserted Id - mysql

My Procedure :
DELIMITER $$
CREATE PROCEDURE `******`.`*********************`
( IN customerName varchar(100),IN customerEmail varchar(100),IN address1 varchar(100),IN address2 varchar(100),
IN zip int,IN city varchar(100),IN state varchar(100),IN country varchar(100),IN region varchar(100),OUT customerId int)
BEGIN
Declare custId int default 0;
Declare zipExist int default 0;
Select Count(*) into zipExist from *****.********** where Zip_Code = zip;
if zipExist = 0 then
Insert into *****.**********(Zip_Code,City,State,Country,Region) values(zip,city,state,country,region);
end if;
Insert into *****.**********(Address_1,Address_2,ZIP_Code) values(address1,address2,zip);
SET custId = LAST_INSERT_ID();
if custId > 0 then
Insert into *****.**********(Customer_Name,Customer_Email,Address) values(customerName,customerEmail,custId);
end if;
SET customerId = LAST_INSERT_ID();
END $$
on calling the procedure I am getting this error:
Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'
I am assuming that custId= Last_Insert_Id(); this line is giving me wrong inserted id. hence it is not able to insert into last table.
I would like to know how to get last inserted id after insert.(Address_id is auto-increment).
tables are :
Customer:
CustomerId int auto-increment,
CustomerName varchar,
CustomerEmail varchar,
AddressId int fk references address.AddressId
Address :
AddressId pk int auto-increment,
Address1 varchar,
Address2 varchar,
zip int fk references zipmaster.zip
zipmaster :
zip int pk auto-increment,
city varchar,
state varchar,
country varchar

LAST_INSERT_ID() returns only automatically generated AUTO_INCREMENT values, if the customer_id is not auto-increment you will not get the correct value.
For more information please refer the link :
http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id

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

Stored procedure not working for inserting data

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,'[]','[]'​​);

MySql assigning a select

I am trying to create a MySql function that will tell me how many orders(comanda) have been placed by a client(whose id i will provide as a parameter).
However, I am getting a syntax error that says counter(my decared variable) is not valid at this position, expecting an identifier.
I split the declaration and both assignments of the value just to be sure that this is not the reason for the error. The error triggers at the last assignment of the select.
Can anybody explain what I am doing wrong? Thank you!
create table client
(id int primary key auto_increment,
nume varchar(50),
prenume varchar(50),
oras varchar(50),
judet varchar(50),
strada varchar(50),
cod_postal varchar(50),
nr_tel varchar(50),
email varchar(50)
);
create table comanda
(id int primary key auto_increment,
data_plasare date,
metoda_livrare enum('ridicare personala','livrare la domiciliu','easy box'),
metoda_plata enum('numerar','card la ghiseu','online cu cardul','transfer bancar','PayPal','rate'),
id_client int
);
alter table comanda
add foreign key (id_client) references client(id);
delimiter //
create function clienti_multiple_comenzi(p_id_client int)
returns int
begin
declare counter int;
set counter = 0;
set counter = select count(id)
from comanda
where id_client = p_id_client;
return counter;
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 ;