MySQL - Select INTO variable not working as desired - mysql

I am facing a problem with the select INTO clause-
CREATE PROCEDURE `sp_user_signup`(
IN gender int,
IN dob varchar(50),
IN location int,
IN email varchar(100),
IN password varchar(50),
IN verify_uuid varchar(256),
IN fb_user bool
)
BEGIN
DECLARE User_ID INT DEFAULT 0;
DECLARE ENABLED BOOL DEFAULT TRUE;
SELECT user_id INTO User_ID FROM tbl_user_login WHERE email = email;
CALL sp_debug(ENABLED,1,User_ID,(select concat_ws('',"UserID:", User_ID)));
IF User_ID = 0 THEN
<do something>
ELSE
<do something>
END IF
END
My tbl_user_login has values for email - v.psk#gmail.com.
Even though I pass the email v.psk#gmail.com to SP it always goes into IF BLOCK.
The values of User_ID is zero from the debugs.
Thanks in advance.

This is not doing what you expect:
SELECT user_id INTO User_ID FROM tbl_user_login WHERE email = email;
The problem is that you think one email is a variable and the other a column. SQL can't read your mind though, so both are the column.
Prefix your variables with something to distinguish them from columns. For example:
CREATE PROCEDURE `sp_user_signup`(
IN v_gender int,
IN v_dob varchar(50),
IN v_location int,
IN v_email varchar(100),
IN v_password varchar(50),
IN v_verify_uuid varchar(256),
IN v_fb_user bool
)
BEGIN
DECLARE v_User_ID INT DEFAULT 0;
DECLARE ENABLED BOOL DEFAULT TRUE;
SELECT user_id INTO v_User_ID FROM tbl_user_login WHERE email = v_email;
CALL sp_debug(ENABLED,1,v_User_ID,(select concat_ws('',"UserID:", v_User_ID)));
IF v_User_ID = 0 THEN
<do something>
ELSE
<do something>
END IF
END

Related

I want to increase or decrease the amount of money in Total_Crédit which is in Credit_electrecité depending on the event to be done

create PROCEDURE PR_Credit_Total(
in newidpiece int,
in newnpiece bigint,
in newnop varchar(60),
in newdateengagement date,
in newdatefacture date,
in newlocalité varchar(50),
in newtournee int,
in newnpolice bigint,
in newservice varchar(20),
in newmontant float,
in newecheance varchar(7),
in newcreated varchar(25),
in eventvarchar(100)
)
BEGIN
set #total=(SELECT sum(Total_Crédit) from credit_electricité) ;
if event=='ajouter'
and newtournee is null
THEN
if #total-newmontant>=0
INSERT into vignetteoneep VALUES(newidpiece,newnpiece,newnop,newdateengagement,
newdatefacture,newlocalité,newtournee,newnpolice,newservice,newmontant,newecheance,newcreated);
then
UPDATE credit_electricité set Total_Crédit=Total_Crédit-newmontant;
end if;
end if;
END
create PROCEDURE PR_Credit_Total(
#newidpiece AS int,
#newnpiece AS bigint,
#newnop AS varchar(60),
#newdateengagement AS date,
#newdatefacture AS date,
#newlocalité AS varchar(50),
#newtournee AS int,
#newnpolice AS bigint,
#newservice AS varchar(20),
#newmontant AS float,
#newecheance AS varchar(7),
#newcreated AS varchar(25),
#event AS varchar(100),
#total AS INT
)
AS
BEGIN
set #total=(SELECT sum(Total_Crédit) from credit_electricité)
if #event = 'ajouter' and #newtournee is null
if #total - #newmontant >=0
INSERT into vignetteoneep VALUES(newidpiece,newnpiece,newnop,newdateengagement,
newdatefacture,newlocalité,newtournee,newnpolice,newservice,newmontant,newecheance,newcreated)
UPDATE credit_electricité set Total_Crédit=Total_Crédit - #newmontant
END
Here's a list of syntax errors to fix
in eventvarchar(100) missing space ,should be in event varchar(100) but event is a keyword and best avoided
if event=='ajouter' null safe equal in mysql is <=> so should be if event <=> 'ajouter' but = would do
The second if does not have a then it's not clear if the insert and update should be part of same condition but I suspect not
if #total-newmontant>=0 then
INSERT ...
else
UPDATE ...
end if;
And you may need to set delimiters

if first name not exists in database it should print smessage but it is going else condition and inserting

CREATE DEFINER=`root`#`localhost` PROCEDURE `AddStudent`(in Firstname varchar(50)
,in Lastname varchar(50)
,in email varchar(50)
,out smessage varchar(500) )
BEGIN
SELECT first_name FROM web_student_tracker.student where first_name in (Firstname);
if Firstname=NULL then set smessage="Name not exsists";
else
insert into student(first_name, last_name, email) values(Firstname,Lastname,email);
END IF;
END
It must be is null not = null.
if Firstname is NULL then set smessage="Name not exsists";
To check if firstname exists, you need to copy the rsult to a variable that you check
CREATE DEFINER=`root`#`localhost` PROCEDURE `AddStudent`(in Firstname varchar(50)
,in Lastname varchar(50)
,in email varchar(50)
,out smessage varchar(500) )
BEGIN
SELECT first_name INTO #firstname FROM web_student_tracker.student where first_name in (Firstname);
if #firstname IS NULL then
set smessage="Name not exsists";
else
insert into student(first_name, last_name, email) values(Firstname,Lastname,email);
END IF;
END

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 ;

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 Stored Procedure : Get Last Inserted Id

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