MySQL Using stored procedure in select statement - mysql

I have a stored procedure like so:
$connection->query('
drop procedure if exists listing_count;
create procedure listing_count(IN parent int(11))
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
(select count(*) from listing_category where category in(select id from ids));
end');
$fetch=$connection->query('select *,listing_count(id) as listing_count from category')->fetchall(pdo::FETCH_UNIQUE|pdo::FETCH_ASSOC);
I would like to use my procedure like a function. So that listing_count gets the count so that I can use it. Do I need to create a separate function? Can a procedure get my count and return it?
Turning it into a function like so:
drop function if exists listing_count;
create function listing_count(parent int(11)) returns int(11) deterministic
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
return (select count(*) from listing_category where category in(select id from ids));
end
But this does not work. I am not very familiar with procedures vs functions but I assume that I can't add all the functionality into a function as I can in a procedure.

I would like to use my procedure like a function.
You Can't Do Thatâ„¢.
I suggest you convert your sp to a stored function. That's a good idea in any case because it returns a single value. The way you have it now, it returns a one-column one-row result set. If it were a function it would work easily in every context you need it. In contrast, stored procedures returning result sets are not nearly as easy to use. For example, see this. How to use Table output from stored MYSQL Procedure
Or you could write a stored function to wrap your stored procedure and return the value. In my opinion that is an inferior solution, just because it has extra complexity.

Related

MySQL Get row data from Update query with LIMIT via stored procedure

I have a query which updates multiple rows in a table with a variable LIMIT. I need to get data from the updated rows so I know which exact rows got affected. I wrote this simple procedure:
DELIMITER $$
CREATE PROCEDURE select_update(IN myId INT, IN myAttr VARCHAR(10), IN myAmount MEDIUMINT)
begin
SELECT data FROM mytable WHERE id IS NULL AND attr = myAttr LIMIT myAmount;
UPDATE mytable SET id = myId WHERE id IS NULL AND attr = myAttr LIMIT myAmount;
end$$
DELIMITER ;
Will this SELECT statement always return the exact same rows that the UPDATE statement affects? Is it possible for another user to execute a query while this procedure is running and thus to possibly change the affected rows between the SELECT and UPDATE?
Create a temporary table to hold the primary keys of the rows to be updated.
CREATE PROCEDURE select_update(IN myId INT, IN myAttr VARCHAR(10), IN myAmount MEDIUMINT)
begin
CREATE TEMPORARY TABLE temp_mytable AS
SELECT pk FROM mytable WHERE id IS NULL AND attr = myAttr LIMIT myamnt;
UPDATE mytable JOIN temp_mytable USING (pk)
SET mytable.id = myId;
SELECT mytable.data
FROM mytable JOIN temp_mytable USING (pk);
end$$

In and Out Paramater Confusion in stored procedure of Mysql

I am new to stored procedures in Mysql and working on some basic stored procedures to fetch data from a single table based on multiple conditions. I am a bit confused in IN and OUT parameters which stored procedure accept and returns respectively.
Below is the select statement for which I am creating a stored procedure.
select name from item where id in
(select item_id from stock where created_by_id != processor_id and processor_id in
(select id from users where type ='Manager'));
name is a column in item table from which I want to get data based on a condition. when I am running a above query..it returns me correct output as below.
#name
'Samsung'
'Pant'
but when I am running the same statement using a stored procedure as below.
DROP PROCEDURE IF EXISTS sp_ItemName3;
delimiter //
CREATE PROCEDURE sp_ItemName3 (IN userType varchar(255), OUT Name varchar(255))
BEGIN
select name from item where id in
(select item_id from stock where created_by_id != processor_id and processor_id in
(select id from users where type = userType));
END
//
Call sp_ItemName3('Manager',#Name);
After calling the stored procedure it returns me two NULL rows. what is the reason? mysql workbench is not returning any error/exception.
Correct me..if I am doing something wrong...!!

nested procedures on mysql

I am new to MySQL. I have started making a database with a table Customers which has two procedures.
getprocedure12 which returns name of customer when inputted the customer id
getcustage which returns age of customer when id is inputted.
so I want to make a 3rd procedure calling these two procedures which will output both name and age when id is given.
can you please help me figure out how to get the output I want?
CREATE PROCEDURE `nestedprocedurecustomers` (IN ID INT)
BEGIN
DECLARE (customername varchar(20), customerage INT);
CALL getcustomername12( cust_id, customername);
CALL getcustage( cust_id, customerage);
WHERE cust_id= ID;
END
You can't use WHERE outside a query. There's no need for the cust_id variable, just use id.
Finally, since this procedure doesn't have any OUT parameters, you need to use SELECT to return the variables that were returned by the inner calls.
CREATE PROCEDURE `nestedprocedurecustomers` (IN ID INT)
BEGIN
DECLARE customername varchar(20);
DECLARE customerage INT;
CALL getcustomername12(id, customername);
CALL getcustage(id, customerage);
SELECT customername, customerage;
END

Selecting all values from a table in mysql using a stored procedure

I have a table called Contacts with a field called person_id that I have connected to a java application.
If no value is specified for person_id in the application, I want to select everything from the contacts table using a stored procedure.
The operation I want to perform is this:
Select * from Contacts where (person_id like "%")
For this I have written a stored procedure shown below:
Delimiter $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `selectTest2`(In p_id int(11))
BEGIN
if p_id = null then
set p_id = "%";
end if;
select * from Contacts where (person_id like p_id);
END $$
Delimiter ;
However when I run this procedure in my sql using the following
call selectTest2(null)
The table that is returned is blank. How do I make it show all the values in the table?
The parameter p_id gets its value from a text box in the application. If the user has entered an id, I want the procedure to show only that particular record else I want it to show all records.
What have I done wrong and how do I correct it? I am aware that p_id is an int however I tried the same thing with other fields of type varchar and the table failed to return any value.
Try using case statement in where clause like below
WHERE CASE WHEN p_id IS NOT NULL THEN person_id = p_id ELSE TRUE END
Hope this should solve your problem

MySQL Stored Procedure Cursor based on parameters

I'm not very familiar with MySQL stored procedures, but am attempting to write one for the first time. In my procedure, I have 2 in parameters and one or both of them could be null. I need to create a cursor to loop over, but my cursor needs to be based on the in parameters. Where if 1 is null and the other isn't, my cursor query is different.
For example:
CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
DECLARE cur CURSOR FOR
IF timestamp IS NOT NULL THEN
IF id IS NULL THEN
SELECT columns FROM Table WHERE modified_on <= timestamp
ELSE
SELECT columns FROM Table WHERE userid = id AND modified_on <= timestamp
ELSE
/* Logic here to pull query without the timestamp and where userid matches if the id passed in is not null */
END IF
END
Could someone show me a simple example of how to achieve this?
issue
syntax error, the declare cursor statement requires to be associated with exactly one select query :
DECLARE cursor_name CURSOR FOR select_statement
also Table is a reserved keyword and needs to be escaped ( or use a different name ) in :
SELECT columns FROM Table
to fix, either create two cursors one for each scenario or embed both query paths in one select query
setup
create table `Table`
(
id integer primary key auto_increment not null,
userid integer not null,
modified_on datetime not null
);
fix
-- option one : combine queries into one
drop procedure if exists test;
delimiter $$
CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
DECLARE cur CURSOR FOR SELECT columns FROM `Table` WHERE ( id is null or userid = id ) and modified_on <= timestamp;
-- open and read from cursor..
END$$
delimiter ;
-- option two define two cursors and use conditional logic below to decide which to read from
drop procedure if exists test;
delimiter $$
CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
DECLARE cur1 CURSOR FOR SELECT columns FROM `Table` WHERE modified_on <= timestamp;
DECLARE cur2 CURSOR FOR SELECT columns FROM `Table` WHERE userid = id AND modified_on <= timestamp;
-- evaluate if/else logic here to decide which cursor to open and use..
END$$
delimiter ;
note: not sure what you're planning todo for each cursor fetch. depending on your use case, its possible you can do this without a cursor. if this is the case, dont use a cursor and keep the processing closer to the natural sql set-based processing
reference
mysql declare cursor syntax
ansi sql reserved keywords
mysql cursors