Why is it the output is NULL when i run this mysql programming? - mysql

In this code, i'm trying to output some data when the ci_ty is 'QS'. But the out put is NULL. Can someone help me figure this out?
delimiter //
create procedure GetFnameAndLname(
IN ci_ty VARCHAR(45),
OUT p_id INT,
OUT f_name VARCHAR(45),
OUT l_name VARCHAR(45))
begin
select city into ci_ty
from fathi.personal;
if ci_ty = 'QS' then
select idpersonal,fname,lname into p_id,f_name,l_name
from fathi.personal;
end if;
end
call GetFnameAndLname('QS',#p_id,#f_name,#l_name);
select #p_id,#f_name,#l_name;

Related

Mysql Stored Proc not returning a VARCHAR out parameter

Below is my stored procedure. It works fine but my problem is I can't get the output parameter as VARCHAR.
The part where I'm having problem is the assignment of #curcName to the out parameter op_resultMessage
BEGIN
SET op_resultMessage = #curcName;
END;
Here's the Stored Procedure.
CREATE DEFINER=`root`#`localhost` PROCEDURE `addCurriculum`(
IN p_curcName varchar(100),
IN p_description TEXT,
IN p_yearLevel VARCHAR(50),
IN p_syStart INT,
IN p_syEnd INT,
IN p_creator VARCHAR(50),
OUT op_resultMessage VARCHAR(50))
BEGIN
DECLARE curcName VARCHAR(20) ;
IF EXISTS
(SELECT #curcName := `name`
FROM curriculum
WHERE
yearLevel = p_yearLevel
AND syStart = p_syStart
AND syEnd = p_syEnd )
THEN --
BEGIN
SET op_resultMessage = #curcName;
END;
ELSE
BEGIN
INSERT INTO curriculum(`name`, description, yearLevel, syStart, syEnd, creator)
VALUES(p_curcName,p_description,p_yearLevel,p_syStart,p_syEnd,p_creator);
END;
END IF;
END
I'm trying to return a message IF name EXISTS
So it should go something like
SET op_resultMessage = #curcName 'already uses the school year and year level you're trying to insert';
But I don't know how to properly concatenate and assign values. I'm still confused with := SET and = operators. I guess that's where I'm having problems with.
If I change the out parameter's type to an INT like
OUT op_resultMessage VARCHAR(50)
then assigns a number to op_resultMessage like SET op_resultMessage = 1;
It returns the number 1 as out parameter values. It just won't work with varchar.
So when I try to call the procedure
CALL `enrollmentdb`.`addCurriculum`
('Test Curriculum ','Test ','Grade 1',2015,2016,'jordan',#outputMsg);
SELECT #outputMsg; -- this doesn't return any value even if Grade 1, 2015 and 2016 exists
I'd appreciate any help. I actually just learned mysql recently.
Thanks.
drop procedure if exists addCurriculum;
delimiter $$
CREATE PROCEDURE `addCurriculum`(
IN p_curcName varchar(100),
IN p_description TEXT,
IN p_yearLevel VARCHAR(50),
IN p_syStart INT,
IN p_syEnd INT,
IN p_creator VARCHAR(50),
OUT op_resultMessage VARCHAR(50))
BEGIN
DECLARE curcName VARCHAR(20) ;
SELECT `name` into #curcName
FROM curriculum
WHERE
yearLevel = p_yearLevel
AND syStart = p_syStart
AND syEnd = p_syEnd
LIMIT 1;
-- Note change above. When selecting into a variable (or more than 1)
-- then 0 or 1 rows can come back max or an Error occurs
IF #curcName is not null then
SET op_resultMessage = #curcName;
ELSE
BEGIN
INSERT INTO curriculum(`name`, description, yearLevel, syStart, syEnd, creator)
VALUES(p_curcName,p_description,p_yearLevel,p_syStart,p_syEnd,p_creator);
END;
SET op_resultMessage = 'GEEZ I am right here'; -- Drew added this
END IF;
END$$
delimiter ;
Note the commentary in the stored procedure, especially the part of only 0 or 1 rows returning else an Error will occur with a select into var pattern. So LIMIT 1. That may or may not be the row you want (limit 1), but that is where it is at right now.

SQL procedure return empty table despite of working query

I've a problem with procedure in SQL.
My code in SQL which is working is like that:
SELECT * FROM ble.lampa_elektronowa
WHERE id_typ =
(SELECT id_typ FROM typ
WHERE typ = 'pierwszy')
And the result of this query is
When i'm trying to write the procedure using this code (IF Akcja = 'DODAJ_DATA' THEN):
CREATE DEFINER=`root`#`localhost` PROCEDURE `procedura_lampa`(
IN Akcja VARCHAR(25),
IN id_lampa INT,
IN nazwa_lampy VARCHAR(50),
IN id_pomiar INT,
IN punkt INT,
IN krzywa INT,
IN Ia FLOAT,
IN IsVariable FLOAT,
IN Vg FLOAT,
IN Va FLOAT,
IN Vs FLOAT,
IN Vf FLOAT,
IN id_typ INT,
IN TYP VARCHAR(45),
IN zapas15 INT,
IN zapas16 INT,
IN zapas17 INT,
IN zapas18 INT,
IN zapas19 INT,
OUT Komunikat VARCHAR(200)
)
BEGIN
IF Akcja = 'LISTA' THEN
BEGIN
SELECT * FROM ble.lampa_elektronowa;
SET #Komunikat = 'Wyƛwietlono';
SET Komunikat = #Komunikat;
END;
END IF;
IF Akcja = 'DODAJ_DATA' THEN
BEGIN
INSERT INTO ble.data (data)
VALUES (NOW());
END;
END IF;
IF Akcja = 'WYPELNIJCBIDLAMPY' THEN
BEGIN
SELECT nazwa_lampy FROM ble.lampa_elektronowa
WHERE id_typ =
(SELECT id_typ FROM typ
WHERE typ = TYP);
END;
END IF;
END
and I'm trying to call this procedure using this code:
call procedura_lampa('WYPELNIJCBIDLAMPY', #id_lampy, #nazwa_lampy, #id_pomiar, #punkt, #krzywa, #Ia, #IsVariable, #Vg, #Va, #Vs, #Vf, #id_typ, 'pierwszy', #zapas15, #zapas16, #zapas17, #zapas18, #zapas19, #Komunikat) ;
, the result of the query is empty.
The "typ" table looks like
.
Why it doesn't work?
This should returns some results.
You have two semicolons in your procedure. One after sub query, another after END. Remove the first one for sure. If you still have error let us know what is its content.

MySQL function definition - 'BEGIN' (begin) is not a valid input at this position

I typed this up in verbatim from a textbook on MySQL.
There's a red X denoting an error on the line BEGIN with the text 'BEGIN' (begin) is not a valid input at this position.
The database used is View Ridge Gallery. Is there any obvious issues with the code?
DROP FUNCTION IF EXISTS InsertCustomerAndInterests;
DELIMITER $$
CREATE FUNCTION InsertCustomerAndInterests
(
newLastName Char(25),
newFirstName Char(25),
newAreaCode Char(3),
newPhoneNumber Char(8),
newEmail Varchar(100),
newNationality Char(30)
)
BEGIN
DECLARE varRowCount Int;
DECLARE varArtistID Int;
DECLARE varCustomerID Int;
DECLARE done Int DEFAULT 0;
DECLARE AristCursor CURSOR FOR
SELECT AristID
FROM ARTIST
WHERE Nationality=newNationality;
DECLARE continue HANDLER FOR NOT FOUND SET done = 1;
#Check to see if Customer already exists in datebase
SELECT Count(*) INTO varRowCount
FROM CUSTOMER
WHERE LastName = newLastName
AND FirstName = newFirstName
AND AreaCode = newAreaCode
AND PhoneNumber = newPhoneNumber
AND Email = newEmail;
#IF (varRowCount > 0 ) THEN Customer already exists
IF (varRowCount > 0 )
THEN
ROLLBACK;
SELECT 'Customer already exists';
END IF;
#IF (varRowCount = 0 ) THEN Customer does not exist.
#Insert new Customer data
IF (varRowCount = 0)
THEN
INSERT INTO CUSTOMER (LastName, FirstName, AreaCode, PhoneNumber, Email)
VALUES (newLastName, newFirstName, newAreaCode, newPhoneNumber, newEmail);
#Get new CustomerID surrogate key value
SET varCustomerID = LAST_INSERT_ID();
#Create intersection record for each appropriate Arist.
OPEN AristCursor;
REPEAT
FETCH ArtistCursor INTO varArtistArtistID;
IF NOT done THEN
INSERT INTO CUSTOMER_ARTIST_INT (ArtistID, CustomerID)
VALUES (varArtistID, varCustomerID);
END IF;
UNTIL done END REPEAT;
CLOSE ArtistCursor;
SELECT 'New customer and artist interest data added to database.'
AS InsertCustomerAndInterestsResults;
END IF;
END
$$
DELIMITER ;
You need to add return type before begin and must return value from the function.
DELIMITER $$
DROP FUNCTION IF EXISTS `InsertCustomerAndInterests`$$
CREATE FUNCTION `InsertCustomerAndInterests`(
newLastName CHAR(25),
newFirstName CHAR(25),
newAreaCode CHAR(3),
newPhoneNumber CHAR(8),
newEmail VARCHAR(100),
newNationality CHAR(30)
) RETURNS INT(11) # you missed return type here.
BEGIN
DECLARE done INT DEFAULT 0;
RETURN done; # must match with return type
END$$
DELIMITER ;
Since all functions need a return value and return type, you are missing the RETURNS clause after declaring your parameters. See CREATE FUNCTION

MySQL stored procedure if statement not working

I have the following stored procedure in MySQL
CREATE DEFINER=`test_db`#`%` PROCEDURE `ADD_ATTENDANCE`(IN `programID` INT, IN `clientID` INT, IN `insDate` DATETIME, IN `updDate` DATETIME, IN `insUser` INT, IN `updUser` INT, IN `lessonDate` DATE, IN `lessonTime` TIME)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Add attedance to my calendar'
BEGIN
DECLARE max_sub, availability INT;
DECLARE cursor_max_sub CURSOR FOR SELECT max_sub FROM app_lesson WHERE id = programID;
DECLARE cursor_availability CURSOR FOR SELECT count(*) FROM attendance WHERE program_id = programID AND lesson_date = lessonDate AND lesson_time = lessonTime;
OPEN cursor_max_sub;
OPEN cursor_availability;
read_loop: LOOP
FETCH cursor_max_sub INTO max_sub;
FETCH cursor_availability INTO availability;
IF (availability < max_sub) THEN
insert into attendance (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
LEAVE read_loop;
ELSE
insert into attendance_hold (program_id, client_id, ins_date, upd_date, ins_user, upd_user, lesson_date, lesson_time)
values (programID, clientID, insDate, updDate, insUser, updUser, lessonDate, lessonTime);
END IF;
END LOOP;
CLOSE cursor_max_sub;
CLOSE cursor_availability;
END;
Even though the cursor_max_sub is equal to 6 and the cursor_availability is equal to 4 my procedure always executes the else insert statement. Can you please help me out?
Thanks!!!
OK that was tricky... For some reason when i change the max_sub variable into maxNumberOfSubscription everything worked perfectly... Is max_sub some kind of reserved key word for MySQL or there was a complication because my variable had the same name with the returned field of select statement?

Mysql Function returns Null always

I have a function in mysql like below:
DELIMITER $$
CREATE DEFINER=root#localhost FUNCTION fnGetDropDownValue(
itemValue varchar(300),
DropDownId int,
CId int
) RETURNS int(11)
BEGIN
DECLARE listId int;
SELECT ListID into listId FROM DropDownListValues WHERE LOWER(ListValue) = LOWER(itemValue) AND DropDownListID = DropDownId AND (ClientId = 0 OR ClientId = CId);
RETURN listId;
END$$
But it always returns Null values when I use
SELECT fnGetDropDownValue('General', 24, 18);
I don't know what I am doing wrong :(
After having the case sensitive issue with mysql columns I used to have variable names to start with _ to avoid it messing with column names. Now the stored procedure looks like this:
DELIMITER $$
CREATE DEFINER=root#localhost FUNCTION fnGetDropDownValue(
itemValue varchar(300),
DropDownId int,
CId int
) RETURNS int(11)
BEGIN
DECLARE _listId int;
SELECT ListID into _listId FROM DropDownListValues WHERE LOWER(ListValue) = LOWER(itemValue)
AND DropDownListID = DropDownId AND (ClientId = 0 OR ClientId = CId);
RETURN _listId;
END$$
This way it will work on any platform and it may be useful for others.