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.
Related
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
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,'[]','[]');
I created a table [EMPLOYEE_DATEOFBIRTH] named
CREATE TABLE EMPLOYEE_DATEOFBIRTH (ID int primary key not null,
NAME nvarchar(20) not null,
DATE_OF_BIRTH DATETIME2(7) not null,
GENDER nvarchar(10) not null,
DEP_ID int not null)
and inserted data to this table.
INSERT INTO EMPLOYEE_DATEOFBIRTH (ID, NAME, DATE_OF_BIRTH,GENDER,DEP_ID) VALUES (1,'Jack','1980-12-30 00:00:00.000','MALE',1)
INSERT INTO EMPLOYEE_DATEOFBIRTH (ID, NAME, DATE_OF_BIRTH,GENDER,DEP_ID) VALUES (2,'Ann','1982-09-01 12:02:36.260','FEMALE',2)
Then I created a function which returns list of employee by gender
CREATE FUNCTION fnEmployeeByGender (#Gender nvarchar)
RETURNS TABLE
AS
RETURN
(SELECT ID, NAME, DATE_OF_BIRTH,GENDER,DEP_ID
FROM EMPLOYEE_DATEOFBIRTH
WHERE GENDER=#Gender)
to execute this function I use the query but it doesn't return anything
SELECT * FROM fnEmployeeByGender('MALE')
what may be reason for this? thanks in advance.
Your error is here: #Gender nvarchar. If you don't specify a length for an nvarchar, it defaults to one. So you are only searching for GENDER = 'M'. Solve it by giving a length: #Gender nvarchar(10).
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
I created a database with following tables :
CREATE SCHEMA IF NOT EXISTS `facturatiedatabase` ;
USE `facturatiedatabase` ;
DROP TABLE IF EXISTS tblAddress ;
DROP TABLE IF EXISTS tblContact ;
DROP TABLE IF EXISTS tblCustomers ;
CREATE TABLE tblCustomers (
customerID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
vat VARCHAR(30) NOT NULL,
customerVisible varchar(1) NOT NULL DEFAULT 'T'
) ENGINE=InnoDB;
CREATE TABLE tblContact (
contactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100),
phone VARCHAR(100),
customerID int,
CONSTRAINT FK_customerID_Contact FOREIGN KEY (customerID) REFERENCES tblCustomers(customerID)
) ENGINE=InnoDB;
CREATE TABLE tblAddress (
addressID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
street VARCHAR(100),
houseNumber VARCHAR(15),
city VARCHAR (100),
country VARCHAR (100),
customerID int,
CONSTRAINT FK_customerID_Adress FOREIGN KEY (customerID) REFERENCES tblCustomers(customerID)
) ENGINE=InnoDB;
INSERT INTO tblCustomers (firstname, lastname,vat)
VALUES ("John","Doe","UV45856855");
INSERT INTO tblContact (customerID,phone, email)
VALUES ((SELECT DISTINCT LAST_INSERT_ID() FROM tblCustomers), "0000001","Johndoe#gmail.com");
INSERT INTO tblAddress (customerID,street,housenumber,city,country)
VALUES ((SELECT DISTINCT LAST_INSERT_ID() FROM tblCustomers), "berkenlaan","1a","Harelbeke","Belgie");
But when i try following inner join it gives me the following error :
LIMIT 0, 1000 Error Code: 1052. Column 'customerID' in field list is ambiguous 0.000 sec.
SELECT customerID, firstname, lastname, vat,email
FROM tblCustomers
INNER JOIN tblContact on tblCustomers.customerID = tblContact.contactID
The error message says it all: the column name customerID is contained in both tables. So which value should mysql select? That is ambiguous, therefore the error.
Have a try with this variant:
SELECT tblCustomers.customerID AS customerID, firstname, lastname, vat,email
FROM tblCustomers
INNER JOIN tblContact on tblCustomers.customerID = tblContact.contactID
(or pick that other tables's column with the same if you need that one...)
And, frankly, I doubt your ON clause is the one you want to use. Shouldn't that be ON tblCustomers.customerID = tblContact.customerID instead?