stored procedure with parameters in MYSQL - mysql

I have a question about the stored procedure:
Create a stored procedure named format_currency that accepts a character and a double number. It will return a VARCHAR(32) with the symbol in the front, followed by the number to 2 decimal places.
For example, format_currency('$', 123.4) should return $123.40
Here is my code:
CREATE OR REPLACE PROCEDURE format_currency(IN c VARCHAR2, IN n DOUBLE(9,2))
AS
BEGIN
SELECT CONCAT(c,',' n);
END;
It's not working, I have no idea how to write codes inside BEGIN and END.
Many Thanks for your help.
Henry

Instead of procedure I suggest to use function:
Code:
DELIMITER $$
DROP FUNCTION IF EXISTS test_f$$
CREATE FUNCTION test_f(a varchar(22),b double(9,2)) returns varchar(64)
BEGIN
SET #RET = (select concat(a,b));
return #RET;
END$$
DELIMITER ;
Test Run:
mysql> select test_f('$',123);
+-----------------+
| test_f('$',123) |
+-----------------+
| $123.00 |
+-----------------+
1 row in set (0.10 sec)
mysql>

DELIMITER\\
CREATE PROCEDURE format_currency (a CHAR, b DOUBLE(9,2))
BEGIN
declare ret VARCHAR(32);
set #ret = (SELECT CONCAT(a,b));
select #ret;
END
DELIMITER\\
call format_currency('$',123);

I had a similar question and nothing the other people answered worked for me in MySQL. Here is a working solution with 2 parameters as "SIGN" and "MONEY" and creating a variable called "NEWRESULT" that you delcare, set as 0, and then set as the concat of "SIGN" and "MONEY".
DELIMITER //
CREATE PROCEDURE format_currency`enter code here`
(IN SIGN char(1),IN MONEY double(9,2))
BEGIN
declare NEWRESULT char(8);
set NEWRESULT=0;
SET NEWRESULT=(SELECT CONCAT(SIGN,MONEY));
SELECT NEWRESULT;
END//
DELIMITER ;

Related

How to set varchar datatype in function?

I have an issue in my code where i took this : (ApliEMAIL int) in below code but when i execute function it return empty values because in table i took email filed as varchar.
When i write code with this (ApliEMAIL varchar) it does not create function and gives error.
DELIMITER $$
#DROP FUNCTION IF EXISTS `get_appli_name`$$
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL int)
RETURNS VARCHAR(255)
BEGIN
DECLARE A_NAME VARCHAR(255) DEFAULT"";
SELECT apli_fname INTO A_NAME
FROM tbl_signup
WHERE apli_email = ApliEMAIL;
RETURN A_NAME;
END$$
DELIMITER ;
DELIMITER $$
#DROP FUNCTION IF EXISTS `get_appli_name`$$
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL varchar)
RETURNS VARCHAR(255)
BEGIN
DECLARE A_NAME VARCHAR(255) DEFAULT"";
SELECT apli_fname INTO A_NAME
FROM tbl_signup
WHERE apli_email = ApliEMAIL;
RETURN A_NAME;
END$$
DELIMITER ;
I tested your function. I got this error.
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
By the way, in the future, when you are asking for help with an error, include the error message in your post. Help us to help you! Don't make us guess!
Read the documentation about READS SQL DATA here: https://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html
So I added that option to your function:
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL VARCHAR(255))
RETURNS VARCHAR(255)
READS SQL DATA
BEGIN
DECLARE A_NAME VARCHAR(255) DEFAULT"";
SELECT apli_fname INTO A_NAME
FROM tbl_signup
WHERE apli_email = ApliEMAIL;
RETURN A_NAME;
END$$
It works now:
mysql> select get_appli_name_by_email('thefrog#muppets.org');
+------------------------------------------------+
| get_appli_name_by_email('thefrog#muppets.org') |
+------------------------------------------------+
| Kermit |
+------------------------------------------------+
You are missing the length of the ApliEMAIL-parameter.
Insted of:
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL varchar)
you should have:
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL varchar(255))
..or whatever the length of ApliEMAIL is.
You must add deterministic or reads sql data flag.
DELIMITER $$
CREATE FUNCTION get_appli_name_by_email(ApliEMAIL varchar(50))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
RETURN ifnull((SELECT apli_fname FROM tbl_signup WHERE apli_email = ApliEMAIL LIMIT 1), '');
END$$
DELIMITER ;

My sql function deosn't return count

I have one function written in my sql which returns the count of records based on some id's. But it always returns the value 1950.Here is my query.
CREATE DEFINER=`trajectory`#`%` FUNCTION `fn_ReturnAlreadyPlayedGames`(AppId int(11),AppUserid int(11))
RETURNS int(11)
BEGIN
declare Counting int(11);
set Counting=(
select count(*)
from user_sessions
where appid= 5 and appuserid= 41 and status=1);
RETURN Counting;
END
I have passed static id's for now.when I run this query as plain sql then it returns 8 rows but inside function it always returns 1950.
Please help me in this.Thanks in advance.
there is a little mistake ;)
where appid= 5 and appuserid= 41 and status=1);
you should replace appid and appuserid with your variables
The problem is using the same name for the function parameters and the columns. So use an alias when referring to the columns. Or just rename the function parameters.
DELIMITER $$
CREATE FUNCTION fn_ReturnAlreadyPlayedGames(AppId int(11),AppUserid int(11))
RETURNS int(11)
BEGIN
declare Counting int(11);
set Counting=(select count(*) from user_sessions us where us.appid= 5 and us.appuserid= 41 and us.status=1);
RETURN Counting;
END$$
DELIMITER ;
With the parameters
DELIMITER $$
CREATE FUNCTION fn_ReturnAlreadyPlayedGames(appid_param int(11),appuserid_param int(11))
RETURNS int(11)
BEGIN
declare Counting int(11);
set Counting=(select count(*) from user_sessions us where us.appid= appid_param and us.appuserid= appuserid_param and us.status=1);
RETURN Counting;
END$$
DELIMITER ;

mysql - using stored procedure in select statememt

I have following stored procedure :
mysql> call generateSerial('param1',1,#serial);
Query OK, 0 rows affected (0.00 sec)
mysql> select #serial;
+--------------+
| #serial |
+--------------+
| 100000000033 |
+--------------+
I want to use above #serial for each row from select query, something like:
select #serial ,...
from table_test;
and with each row, #serial are difference by difference procedure execute
I know that procedure can not be executed in select stm
But I also can not using function because I need using a transaction to get #serial
have any chance for me about this case ;
Here is one way creating a second procedure that loops over the table rows and calls the generate serial procedure for each row.
CREATE PROCEDURE run()
BEGIN
DECLARE serial VARCHAR(32);
DECLARE col_int INT;
DECLARE col_varchar VARCHAR(10);
DECLARE done INT DEFAULT FALSE;
DECLARE query CURSOR FOR SELECT column_int, column_varchar FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN query;
q: LOOP
FETCH query into col_int, col_varchar;
IF done THEN
LEAVE q;
END IF;
CALL GenerateSerial(col_varchar,col_int,serial);
select serial;
END LOOP;
CLOSE query;
END;
SQL Fiddle

Mysql stored procedure multiple selects

I am running a stored procedure. The issue seems to be that it will go into the if statement. Also for some reason or another regardless of how many selects I use it will only return the first. I've copied this from another stored procedure that works like a charm, but this one just won't go. Any ideas?
DROP PROCEDURE IF EXISTS genSelPriceTier;
DELIMITER $$
CREATE PROCEDURE genSelPriceTier(tier_id INT, default_id INT)
BEGIN
DECLARE rowCount INT DEFAULT 0;
SELECT * FROM price_tier WHERE price_tier_id = tier_id;
SET rowCount = FOUND_ROWS();
IF rowCount < 1 THEN
SELECT * FROM price_tier WHERE price_tier_id = default_id;
END IF;
END$$
DELIMITER ;
There is a bug reported related to the usage of FOUND_ROWS(). So, I recommend using Count(*) for the number of rows returned. Something like the following should work.
DROP PROCEDURE IF EXISTS genSelPriceTier;
DELIMITER $$
CREATE PROCEDURE genSelPriceTier(tier_id INT, default_id INT)
BEGIN
DECLARE rowCount INT DEFAULT 0;
SELECT COUNT(*) INTO rowCount FROM price_tier WHERE price_tier_id = tier_id
IF rowCount < 1 THEN
SELECT * FROM price_tier WHERE price_tier_id = default_id;
END IF;
END$$
DELIMITER ;

Getting errors when trying to create a PROCEDURE in mysql

I am trying to create a mysql stored procedure, but I get this error:
Script line: 2 Failed to CREATE PROCEDURE proc_test_bideep
The stored procedure code is:
DELIMITER $$
DROP PROCEDURE IF EXISTS `commun`.`insert_categorie` $$
CREATE PROCEDURE `commun`.`insert_categorie` (id_mere INT,
lib_categ VARCHAR(50),
id_categ_sup INT ,
categ_authInstantBuy INT)
BEGIN
SET #bg_mere := (SELECT categ_bg FROM categ_basic WHERE categ_id = id_mere);
#bg_mere+2,categ_level_bideep,categ_statut,categ_adult,categ_authSmallBid,categ_authBid,categ_authInstantBuy);
SELECT '1' AS code_retour; END IF;
ecetera.........
END $$
DELIMITER ;
a) You need to DECLARE any variables on the first lines of the procedure, including their datatype:
DECLARE bg_mere INT;
b) To fetch a value from the database into a variable, you use SELECT ... INTO syntax:
SELECT categ_bg INTO bg_mere FROM categ_basic WHERE categ_basic.categ_id = id_mere;
c) You have an END IF without the corresponding IF.
d) The closing END needs a semicolon (not BEGIN though), only then do you need a delimiter to finish the entire statement, and finally you should reset the delimiter back to normal:
BEGIN
# body of the stored procedure goes here
END;
$$
DELIMITER ;
Your parameters are missing the keyword IN such as: ...(IN id_mere INT, IN lib_categ ...). Also, you need to configure your OUT variable for #bg_mere in the initial parameter list such as (IN xxx, ..., OUT bg_mere VARCHAR/INT/WHATEVER).