Stored procedure using insert and select statements - mysql

I want to get the adminID from ADMIN table using the email and save the adminID in the product table. I tried do that, it returns null in the adminID in Product table. Please let me know where I'm making a mistake.
CREATE PROCEDURE prc_saveProduct
(
IN inputuserEmail VARCHAR(255),
inputproductName VARCHAR(255),
inputpoints INT(11),
)
BEGIN
SET #AdminID = (SELECT AdminID FROM ADMIN WHERE email = inputuserEmail );
INSERT INTO PRODUCTS(AdminID, productName, points)
VALUES (#AdminID, inputproductName, inputpoints);
END

This will work.
DELIMITER $$
CREATE PROCEDURE `yourSchema`.`prc_saveProduct`(
p_inputuserEmail VARCHAR(255),
p_inputproductname VARCHAR(255),
p_inputpoints INT(11)
)
BEGIN
DECLARE _AdminID VARCHAR(255);
SELECT
AdminID FROM ADMIN WHERE email = p_inputuserEmail
INTO
_AdminID;
INSERT INTO PRODUCTS(
AdminID,
productName,
points
)
VALUES
(
_AdminID,
p_inputproductName,
p_inputpoints
);
END$$
DELIMITER ;
the p_ is not necessary, I just like to prepend proc params with it to distinguish it. The underscore I like to use for local variables "_AdminID", but that's not necessary either. I just prefer those naming conventions.

Related

MySQL: insert procedure, with variable from another table

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 ;

How to format this MySQL stored procedure?

I'm having difficulty formatting this MySQL stored procedure, I've written SQL Server stored procedures but mysql keeps causing issues. Can anyone that has experience in this take a look and let me know what formatting I'm missing?
CREATE PROCEDURE dbo.spInsertPropertyAndUnit (
IN AccountId INTEGER,
IN Address VARCHAR(255),
IN AddressNumber VARCHAR(255),
IN City VARCHAR(255),
IN State VARCHAR(255),
OUT PropertyId INTEGER
)
BEGIN
DECLARE PropertyId INTEGER;
-- make property
INSERT INTO tblProperties
(Address, AddressNumber, City, State)
VALUES (
IFNULL(Address, ''),
IFNULL(AddressNumber, ''),
IFNULL(City, ''),
IFNULL(State, '')
)
SET PropertyId = CAST(SCOPE_IDENTITY() AS INTEGER)
-- make a default unit
INSERT INTO tblUnits (PropertyId, UnitNumber)
VALUES (PropertyId, 1)
-- Make an Accountpropertymembership
INSERT INTO tblAccountPropertyMemberships (AccountId, PropertyId, MembershipRoleId)
VALUES (AccountId, PropertyId, 0)
SELECT PropertyId FROM tblProperties WHERE PropertyId = #PropertyId
END
The function to get the last auto-increment ID is LAST_INSERT_ID().
You can't use #PropertyID to access a declared variable named PropertyID. Similarly, you can't use #AccountID to access the AccountID parameter.
You don't need to declare the variable PropertyID, since it's already declared as an OUT parameter.
You need ; at the end of each statement. Use the DELIMITER directive to specify an alternate query delimiter, so you can use ; within the procedure.
At the end, you can simply use SELECT PropertyId to return the value of the variable, you don't need to query the table itself.
DELIMITER $$
CREATE PROCEDURE dbo.spInsertPropertyAndUnit (
IN AccountId INTEGER,
IN Address VARCHAR(255),
IN AddressNumber VARCHAR(255),
IN City VARCHAR(255),
IN State VARCHAR(255),
OUT PropertyId INTEGER
)
BEGIN
PropertyId INTEGER;
-- make property
INSERT INTO tblProperties
(Address, AddressNumber, City, State)
VALUES (
IFNULL(Address, ''),
IFNULL(AddressNumber, ''),
IFNULL(City, ''),
IFNULL(State, '')
);
SET PropertyId = LAST_INSERT_ID();
-- make a default unit
INSERT INTO tblUnits (PropertyId, UnitNumber)
VALUES (PropertyId, 1);
-- Make an Accountpropertymembership
INSERT INTO tblAccountPropertyMemberships (AccountId, PropertyId, MembershipRoleId)
VALUES (AccountId, PropertyId, 0);
SELECT PropertyId;
END
$$
DELIMITER ;

mysql insert bigint variable into tinyint type column

I've got tables users and devices with a user_id columns which are tinyint(3).
I have to create a procedure which will add new user and update these tables with user_id. So I set the delimiter to // and make this:
create procedure add_user (in pr_name varchar(15), in pr_surname varchar(15), in pr_address varchar(15), in pr_pesel float(11,0), in pr_tel int (9), in pr_package_id tinyint(3) unsigned, in pr_mac varchar(17), in pr_model varchar(15), in pr_ip int(10) unsigned)
begin
set #date = curdate();
insert into users values (null, pr_name, pr_surname, pr_address, pr_pesel, pr_tel, pr_package_id);
set #id = last_insert_id()
insert into devices (pr_mac, pr_ip, #id, pr_model, #date);
end;//
I want to take last added user_id from users (which is first column in users and is also auto-increment) and put it into user_id in devices table. Mysql returns an syntax error near 'null, #id, pr_model, #date); end'.
I think it's because last_insert_id() function returns bigint unsigned.
Please help me with this.

MySQL Stored procedure IN parameter issue

In my Mysql , I have written below stored procedure to insert data into user table,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
When i test this procedure as below,
CALL `CreateUser1`('ab1#ansys.com' , 'abcdefgh' ,'abc#gmail.com', 'sa' , '' ,'123456789','hasghsdfhgfhgfhdgfhdsgsh');
SELECT * FROM `um.user` WHERE email='ab1#ansys.com';
It does nothing.
It doesn't insert data into table, I figured out the issue .
The isssue is in parameter "Email".
But when I change the parameter "Email" to "Email12" , it worked as expected.
But I don't want to change in parameter as it will be a change in my API as well,
Now i want to solve this issue in sp level as well, I have tried below changes as well in SP which also doesn't works,
Set #userEmail=Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=#userEmail)THEN
Any suggestions
Regards
Sangeetha
You may also qualify their identifiers. See 9.2.1 Identifier Qualifiers.
...
/*
-- You can also use Alias
SELECT `user_id`
FROM `um.user` `uu`
WHERE `uu`.`email` = `Email`
*/
IF NOT EXISTS (SELECT `user_id`
FROM `um.user`
WHERE `um.user`.`email` = `Email`) THEN
...
SQL Fiddle demo unqualified
SQL Fiddle demo qualified
Try this if you want to handle your issue within the stored procedure itself, without changing the name of parameter,
DELIMITER $$
DROP PROCEDURE IF EXISTS `CreateUser1`$$
CREATE PROCEDURE `CreateUser1`(
IN Email VARCHAR(50),
IN Password1 VARCHAR(50),
IN FirstName VARCHAR(50),
IN LastName VARCHAR(50),
IN AlternateEmail VARCHAR(50),
IN PhoneNumber VARCHAR(50),
IN Token VARCHAR(500)
)
BEGIN
DECLARE Email1 VARCHAR(50);
SET Email1 = Email;
IF NOT EXISTS( SELECT user_id FROM `um.user` WHERE `email`=Email1)THEN
INSERT INTO `um.user`(site_id,email,PASSWORD,alternate_email,first_name,last_name,contact_number,
created_on,updated_on,is_active,token,is_verified_email)
VALUES
(1, Email1 , Password1 ,AlternateEmail, FirstName , LastName ,PhoneNumber,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,Token,0);
END IF;
END$$
DELIMITER ;
This is because in MySQL, the parameter name passed to a Stored Procedure should not be the same as Column Name. Hope this solves your problem :)

mysql Insert Statements in Stored Procedure not Inserting

I created a stored procedure which should perform the following:
Insert into Agencies Table, creating an id in the PK index row
Save the id in a variable
Insert the id and other data into Users table
The syntax below does not trigger any errors:
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END
However, the Stored Proc doesn't insert my parameters into the tables when executed. So, after searching I try to create the SP like this (including $$ after "END" and resetting the delimiter to a semi-colon ):
DELIMITER $$
CREATE PROCEDURE insertNewAgencyAndAdmin (IN aName varchar (100), IN numTrav int, IN polType int, IN uEmail varchar(255), IN uFName varchar(40), IN uLName varchar(40), IN uTitle varchar(100))
BEGIN
INSERT INTO btsAgency.Agencies (agencyName, numTrav, polType) VALUES (#aName, #numTrav, #polType);
SET #agencyID = (SELECT agencyID from btsAgency.Agencies where agencyID = LAST_INSERT_ID());
INSERT INTO btsUsers.Users (userAgencyID, userEmail, userFirstName, userLastName, userTitle ) VALUES
(#agencyID, #uEmail, #uFName, #uLName, #uTitle);
END $$
DELIMITER ;
MySql creates the Stored Proc but gives me the following error:
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 'DELIMITER' at line 1
When I execute the created Stored Proc it still doesn't insert the data in my parameters.
Any help would be appreciated.
Some problems in your stored procedure:
It is important to indicate the difference between 9.4. User-Defined Variables and routine parameters 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax, are different variables (eg.: aName != #aName).
Avoid naming parameters or variables as columns of your tables.
DELIMITER $$
CREATE PROCEDURE `insertNewAgencyAndAdmin` (
/*
IN `aName` varchar (100),
IN `numTrav` int,
IN `polType` int,
IN `uEmail` varchar(255),
IN `uFName` varchar(40),
IN `uLName` varchar(40),
IN `uTitle` varchar(100)
*/
IN `_aName` varchar (100),
IN `_numTrav` int,
IN `_polType` int,
IN `_uEmail` varchar(255),
IN `_uFName` varchar(40),
IN `_uLName` varchar(40),
IN `_uTitle` varchar(100)
)
BEGIN
/*
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
#`aName`,
#`numTrav`,
#`polType`
);
*/
INSERT INTO `btsAgency`.`Agencies` (
`agencyName`,
`numTrav`,
`polType`
) VALUES (
`_aName`,
`_numTrav`,
`_polType`
);
/*
SET #`agencyID` = (SELECT `agencyID` from `btsAgency`.`Agencies` where `agencyID` = LAST_INSERT_ID());
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
#`agencyID`,
#`uEmail`,
#`uFName`,
#`uLName`,
#`uTitle`
);
*/
INSERT INTO `btsUsers`.`Users` (
`userAgencyID`,
`userEmail`,
`userFirstName`,
`userLastName`,
`userTitle`
) VALUES (
LAST_INSERT_ID(),
`_uEmail`,
`_uFName`,
`_uLName`,
`_uTitle`);
END$$
DELIMITER ;
SELECT * FROM discounts $$
delimiter $$;
CREATE PROCEDURE insertData(IN id int,IN title varchar(255),IN amount decimal)
BEGIN
insert into discounts values (id,title,amount);
END; $$
call insertData(3,"sadasd",56);
/*DROP PROCEDURE insertData */