Run different SQL statements using If Then with a variable - mysql

Trying to do something very simple. Using If/Then, is there a way to run a separate Select statement based on the value of a variable?
The function GetTotalActiveUnits() in the below code returns an integer.
set #RetVal = GetTotalActiveUnits(CustomerCode);
if #RetVal = 0 then
Select * from tblREF_UnitInfo;
else
select * from tblREF_State;
end if

There is no problem with your code - at least as far as IF is concerned and if it is in a stored routine.
drop procedure if exists p;
delimiter $$
create procedure p(inp int)
begin
set #RetVal = inp;# GetTotalActiveUnits(CustomerCode);
if #RetVal = 0 then
select #retval ;
else
select #retval ;
end if ;
end $$
delimiter ;
call p(1);
+---------+
| #retval |
+---------+
| 1 |
+---------+
1 row in set (0.001 sec)
call p(0)
+---------+
| #retval |
+---------+
| 0 |
+---------+
1 row in set (0.001 sec)

Related

Returning a value using a cursor mysql

DELIMITER $
DROP PROCEDURE IF EXISTS GET_AVG$
CREATE PROCEDURE GET_AVG()
BEGIN
DECLARE l_avg decimal;
DECLARE iam_done int DEFAULT 0;
DECLARE avg_cursor CURSOR FOR
SELECT AVG(score)
FROM score
GROUP BY student_id
;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET iam_done=1;
BEGIN
OPEN avg_cursor;
tbl_loop:LOOP
FETCH avg_cursor INTO l_avg;
IF iam_done = 1 THEN
leave tbl_loop;
END IF;
SELECT l_avg;
END LOOP tbl_loop;
CLOSE avg_cursor;
END;
END$
DELIMITER ;
++++++++++++++++++++++++++++++++++++++++++
My output is not giving me the right values:
mysql> call get_avg();
+----------------+
| #l_avg |
+----------------+
| 0x |
+----------------+
1 row in set (0.00 sec)
+----------------+
| #l_avg |
+----------------+
| 0x |
+----------------+
1 row in set (0.00 sec) ...
++++++++++++++++++++++++++++++++++++++++++
Any idea why I am having a "0x" as returned value?

How to update table using execute statement?

I have two tables (much simplified here):
QUADRI
ID SBR_750 b10C TGI
---------------------
Q1 0 1 0
Q2 2 1 0
Q3 1 0 1
CELLE
CELLANAME NEEDED READY
----------------------
SBR_750 NULL 12
b10C NULL 10
TGI NULL 5
I want this result in CELLE:
CELLANAME NEEDED READY
------------------------
SBR_750 3 12
b10C 2 10
TGI 1 5
I tried to write a stored procedure but it doesn't works: ERROR 1210. Incorrect arguments to EXECUTE.
Here is the code:
CREATE DEFINER=`root`#`%.zamberlan.local` PROCEDURE `AggiornaCelle`(IN nomecella varchar(15))
BEGIN
set #s='update celle set needed=(select sum(?) from quadri) where cellaname=?';
set #NC=nomecella;
prepare stmt from #s;
execute stmt using #NC;
deallocate prepare stmt;
END
UPDATE:
It doesn't work so I change strategy:
CREATE DEFINER=`root`#`%.zamberlan.local` PROCEDURE `AggiornaCelle`()
BEGIN
declare i int;
declare num_rows int;
declare col_name varchar(20);
DECLARE col_names CURSOR FOR
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = quadri
ORDER BY ordinal_position;
select FOUND_ROWS() into num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
CLOSE col_names;
LEAVE the_loop;
END IF;
FETCH col_names
INTO col_name;
update celle set needed=sum(col_name) where cellaname=col_name;
SET i = i + 1;
END LOOP the_loop;
END
inspired by mysql, iterate through column names.
However I receive the error "Cursor is not open..."
You do need to use dynamic sql to do this. Celle knows about all the columns it needs from quadri so you could drive the creation of the dynamic statements from this fact. Using a cursor is as good a way to do it as any.
drop table if exists quadri;
create table quadri(ID varchar(2),SBR_750 int, b10C int, TGI int);
insert into quadri values
('Q1' , 0 , 1 , 0),
('Q2' , 2 , 1 , 0),
('Q3' , 1 , 0 , 1);
drop table if exists celle;
create table CELLE (CELLANAME varchar(20) ,NEEDED int,READY int);
insert into celle values
('SBR_750' , NULL , 12),
('b10C' , NULL , 10),
('TGI' , NULL , 5);
drop procedure if exists `AggiornaCelle`;
delimiter $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `AggiornaCelle`()
begin
DECLARE done INT DEFAULT FALSE;
declare col_name varchar(20);
declare cur1 CURSOR FOR
SELECT cellaname FROM celle ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open cur1;
read_loop: loop
fetch cur1 into col_name;
if done then leave read_loop; end if;
set #sqlstr = concat('update celle set needed = (select sum(',col_name,') from quadri) where cellaname = ', char(39),col_name,char(39),';');
insert into debug_table (msg) values(#sqlstr);
prepare stmt from #sqlstr;
execute stmt ;
deallocate prepare stmt;
end loop;
close cur1;
end $$
delimiter ;
truncate table debug_table;
call `AggiornaCelle`();
select * from debug_table;
select * from celle;
MariaDB [sandbox]> select * from debug_table;
+----+------------------------------------------------------------------------------------------+------+
| id | msg | MSG2 |
+----+------------------------------------------------------------------------------------------+------+
| 1 | update celle set needed = (select sum(SBR_750) from quadri) where cellaname = 'SBR_750'; | NULL |
| 2 | update celle set needed = (select sum(b10C) from quadri) where cellaname = 'b10C'; | NULL |
| 3 | update celle set needed = (select sum(TGI) from quadri) where cellaname = 'TGI'; | NULL |
+----+------------------------------------------------------------------------------------------+------+
3 rows in set (0.00 sec)
MariaDB [sandbox]> select * from celle;
+-----------+--------+-------+
| CELLANAME | NEEDED | READY |
+-----------+--------+-------+
| SBR_750 | 3 | 12 |
| b10C | 2 | 10 |
| TGI | 1 | 5 |
+-----------+--------+-------+
3 rows in set (0.00 sec)
The debug_table only exists so that I can check the update statements.
As per documentation
set #s='update celle set needed=(select sum(?) from quadri) where cellaname=?';
You are supposed to pass two argument.
execute stmt using #NC;
should be or something similar
execute stmt using #NC, #NC;
#NC would be same as you are trying to update a row in celle, which is same as column name in quadri table.

sql if-else procedure prob, cant create procedure

delimiter//
create procedure exercise(out stat char(10),out fee double)
begin
if stat=='AC executive' then set fee=100;
else if stat=='AC Economi' then set fee=50;
else set saldo=20;
end if;
end//
delimiter;
Your if-else if is not correct it should be
if condition then do something
elseif condition then do something
else do something
There is no space between elseif. Also I suppose you mean fee not saldo in the else part. And out stat char(10) should be in stat varchar(100), since you are using the param as input
delimiter //
create procedure exercise(in stat varchar(100),out fee double)
begin
if stat ='AC executive' then set fee=100;
elseif stat = 'AC Economi' then set fee=50;
else set fee=20;
end if;
end;//
delimiter;
Here is a test on mysql
mysql> delimiter //
mysql> create procedure exercise(in stat varchar(100),out fee double)
-> begin
-> if stat ='AC executive' then set fee=100;
-> elseif stat = 'AC Economi' then set fee=50;
-> else set fee=20;
-> end if;
-> end;//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call exercise('AC executive',#o);
Query OK, 0 rows affected (0.00 sec)
mysql> select #o ;
+------+
| #o |
+------+
| 100 |
+------+
1 row in set (0.00 sec)

MySQL create stored procedure syntax with delimiter

I am trying to create a stored procedure in MySQL using a delimiter like this:
use am;
DELIMITER $$
CREATE PROCEDURE addfields()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE acc INT(16);
DECLARE validId INT DEFAULT 0;
END $$
DELIMITER ;
It gives me an error:
#1304 - PROCEDURE addfields already exists
What is the proper syntax for making a stored procedure with a delimiter and dropping it if it exists first?
Getting started with stored procedure syntax in MySQL (using the terminal):
1. Open a terminal and login to mysql like this:
el#apollo:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql>
2. Take a look to see if you have any procedures:
mysql> show procedure status;
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db | Name | Type | Definer | Modified | Created | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb | sp_user_login | PROCEDURE | root#% | 2013-12-06 14:10:25 | 2013-12-06 14:10:25 | DEFINER | | utf8 | utf8_general_ci | latin1_swedish_ci |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.01 sec)
I have one defined, you probably have none to start out.
3. Change to the database, delete it.
mysql> use yourdb;
Database changed
mysql> drop procedure if exists sp_user_login;
Query OK, 0 rows affected (0.01 sec)
mysql> show procedure status;
Empty set (0.00 sec)
4. Ok so now I have no stored procedures defined. Make the simplest one:
mysql> delimiter //
mysql> create procedure foobar()
-> begin select 'hello'; end//
Query OK, 0 rows affected (0.00 sec)
The // will communicate to the terminal when you are done entering commands for the stored procedure. the stored procedure name is foobar. it takes no parameters and should return "hello".
5. See if it's there, remember to set back your delimiter!:
mysql> show procedure status;
->
->
Gotcha! Why didn't this work? You set the delimiter to // remember? Set it back to ;
6. Set the delimiter back and look at the procedure:
mysql> delimiter ;
mysql> show procedure status;
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db | Name | Type | Definer | Modified | Created | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb | foobar | PROCEDURE | root#localhost | 2013-12-06 14:27:23 | 2013-12-06 14:27:23 | DEFINER | | utf8 | utf8_general_ci | latin1_swedish_ci |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
7. Run it:
mysql> call foobar();
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Hello world complete, lets overwrite it with something better.
8. Drop foobar, redefine it to accept a parameter, and re run it:
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)
mysql> show procedure status;
Empty set (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar (in var1 int)
-> begin select var1 + 2 as result;
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call foobar(5);
+--------+
| result |
+--------+
| 7 |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Nice! We made a procedure that takes input, modifies it, and does output. Now lets do an out variable.
9. Remove foobar, Make an out variable, run it:
mysql> delimiter ;
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar(out var1 varchar(100))
-> begin set var1="kowalski, what's the status of the nuclear reactor?";
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call foobar(#kowalski_status);
Query OK, 0 rows affected (0.00 sec)
mysql> select #kowalski_status;
+-----------------------------------------------------+
| #kowalski_status |
+-----------------------------------------------------+
| kowalski, what's the status of the nuclear reactor? |
+-----------------------------------------------------+
1 row in set (0.00 sec)
10. Example of INOUT usage in MySQL:
mysql> select 'ricksays' into #msg;
Query OK, 1 row affected (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar (inout msg varchar(100))
-> begin
-> set msg = concat(#msg, " never gonna let you down");
-> end//
mysql> delimiter ;
mysql> call foobar(#msg);
Query OK, 0 rows affected (0.00 sec)
mysql> select #msg;
+-----------------------------------+
| #msg |
+-----------------------------------+
| ricksays never gonna let you down |
+-----------------------------------+
1 row in set (0.00 sec)
Ok it worked, it joined the strings together. So you defined a variable msg, passed in that variable into stored procedure called foobar, and #msg was written to by foobar.
Now you know how to make stored procedures with delimiters. Continue this tutorial here, start in on variables within stored procedures: http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
Here is the sample MYSQL Stored Procedure with delimiter and how to call..
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`#`%` PROCEDURE `sp_user_login`(
IN loc_username VARCHAR(255),
IN loc_password VARCHAR(255)
)
BEGIN
SELECT user_id,
user_name,
user_emailid,
user_profileimage,
last_update
FROM tbl_user
WHERE user_name = loc_username
AND password = loc_password
AND status = 1;
END $$
DELIMITER ;
and call by, mysql_connection specification and
$loginCheck="call sp_user_login('".$username."','".$password."');";
it will return the result from the procedure.
Here is my code to create procedure in MySQL :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName
(add joins OR sub query as per your requirement)
Where (where condition here)
END $$
DELIMITER ;
To call this procedure use this query :
call procedureName(); // without parameter
call procedureName(id,pid); // with parameter
Detail :
1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.
Read here for more detail
I have created a simple MySQL procedure as given below:
DELIMITER //
CREATE PROCEDURE GetAllListings()
BEGIN
SELECT nid, type, title FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;
Kindly follow this. After the procedure created, you can see the same and execute it.
MY SQL STORED PROCEDURE CREATION
DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin
select * from users
where id=UserId ;
END $$
DELIMITER ;

MySQL save results of EXECUTE in a variable?

How do I save the results of EXECUTE statement to a variable? Something like
SET a = (EXECUTE stmtl);
If you want to do this with a prepared statement, then you need to include the variable assignment in the original statement declaration.
If you want to use a stored routine it's easier. You can assign the return value of a stored function directly to a variable, and stored procedures support out parameters.
Examples:
Prepared Statement:
PREPARE square_stmt from 'select pow(?,2) into #outvar';
set #invar = 1;
execute square_stmt using #invar;
select #outvar;
+---------+
| #outvar |
+---------+
| 1 |
+---------+
DEALLOCATE PREPARE square_stmt;
Stored Function:
delimiter $$
create function square_func(p_input int) returns int
begin
return pow(p_input,2);
end $$
delimiter ;
set #outvar = square_func(2);
select #outvar;
+---------+
| #outvar |
+---------+
| 4 |
+---------+
Stored Procedure:
delimiter $$
create procedure square_proc(p_input int, p_output int)
begin
set p_output = pow(p_input,2);
end $$
delimiter ;
set #outvar = square_func(3);
call square_proc(2,#outvar);
select #outvar;
+---------+
| #outvar |
+---------+
| 9 |
+---------+