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
Related
I have two tables:
CREATE TABLE userTypes (
id INTEGER NOT NULL PRIMARY KEY,
type VARCHAR(50) NOT NULL
);
CREATE TABLE users (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) NOT NULL,
userTypeId INTEGER NOT NULL,
FOREIGN KEY (userTypeId) REFERENCES userTypes(id)
);
INSERT INTO userTypes (id, type) VALUES (0, 'free');
INSERT INTO userTypes (id, type) VALUES (1, 'paid');
I want to create a procedure where that it inserts a user in the users table, with :
id is auto incremented.
email is equal to the email parameter.
userTypeId is the id of the userTypes row whose type attribute is equal to the type parameter
The INSERT function doesn't work with WHERE, so I tried to add a UPDATE but it's not working. Here's what I have for the moment:
DELIMITER //
CREATE PROCEDURE insertUser(
IN type VARCHAR(50),
IN email VARCHAR(50)
)
BEGIN
INSERT INTO users(id, email, userTypeID) VALUES (LAST_INSERT_ID(), email, userTypeID);
UPDATE users SET users.userTypeID = usertypes.id
WHERE usertypes.type = type;
END//
DELIMITER ;
The expected result should be something like this:
CALL insertUser('free', 'name_1#mail.com');
CALL insertUser('paid', 'name_2#mail.com');
SELECT * FROM users;
id email userTypeId
------------------------------------------
1 name_1#mail.com 0
2 name_2#mail.com 1
Leave out the auto_increment-column. As the name suggests, the db will fill this automatically.
Then, use different names for the parameters than the column names. You can use a prefix with the parameters.
Additionally, you could consider using the userTypeId integer value as parameter instead of the textual value. Otherwise you need to handle the situation where the passed type is not among the types in the userTypes (create a new one/reject insert).
DELIMITER //
CREATE PROCEDURE insertUser(
in_type VARCHAR(50),
in_email VARCHAR(50)
)
BEGIN
INSERT INTO users(email, userTypeID)
SELECT in_email, id
FROM userTypes
WHERE type=in_type;
IF (ROW_COUNT()=0) THEN
SELECT 'Error';
ELSE
SELECT 'OK';
END IF;
END//
DELIMITER ;
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 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 ;
I want to select values from basic2 and insert into basic3 and basic4 using stored procedure.
These are the table definitions:
create table basic2(
id int AUTO_INCREMENT,
name varchar(50),
address varchar(50),
PRIMARY KEY (id)
);
create table basic3(
id int AUTO_INCREMENT,
name varchar(50),
address varchar(50),
PRIMARY KEY (id)
);
create table basic4(
id int AUTO_INCREMENT,
name varchar(50),
address varchar(50),
PRIMARY KEY (id)
);
this is the new_person store procedure
drop procedure if exists new_person;
DELIMITER //
CREATE PROCEDURE new_person
select (id, name,address)
from basic2;
BEGIN
START TRANSACTION;
INSERT INTO basic3 (id,name,address)
VALUES(LAST_INSERT_ID(),bname,baddress);
INSERT INTO basic4 (id,name,address)
VALUES(LAST_INSERT_ID(),bname,baddress);
COMMIT;
END//
DELIMITER;
We can do it by two way one for using cursor and another is using SELECT with insert i thing for you SELECT is better
Like this
INSERT INTO basic3 (name,address)
SELECT name, address FROM basic2;
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