stored procedure that takes Query results as parameter - mysql

i just created a stored procedure that take a parameter(example id) and copies columns related to that id from one table to another table.
How can i create stored procedure that takes sub query results as parameter,database is mysql..
This is my example..i want to pass query that select id from table to procedure..
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sasi`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sasi`(IN idno int(4))
BEGIN
INSERT INTO user5(id,email,address,fullname,gender,phonenumber)
SELECT id,email,address,fullname,gender,phonenumber FROM user1 where id != idno;
END$$
DELIMITER ;
call sasi(4);

To pass the results of a query into your stored procedure, wrap the query in brackets.
For example:
call sasi((select max(id) from sometable where somecondition));
You must make sure the query only returns one row and one column.
Edited:
If you want to call the procedure multiple times, once for each row, change your procedure to be a FUNCTION:
CREATE FUNCTION sasi(idno int(4))
RETURNS int(4)
BEGIN
INSERT INTO user5(id,email,address,fullname,gender,phonenumber)
SELECT id,email,address,fullname,gender,phonenumber FROM user1 where id != idno;
RETURN idno;
END
Then call it like this:
select sasi(id)
from table
where ...
sasi(id) will get called for every row matching the where clause.

Related

Need to Create MySQL Procedure for getting data from table based on condition and insert them into another table

Using a single MySQL procedure i need to write queries to get data from a table (where the results can be of a list also) after getting the results,need to insert those selected rows into another table of the same database..I'm finding dificulty in getting the result of the select query and fetching values to insert into another table...
Iam able to do the above one if it returns only one row but in my case it can return any number of rows...
DELIMITER $$
USE `scmn_nov21`$$
DROP PROCEDURE IF EXISTS `procedure1`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `procedure1`(
IN Param1 VARCHAR(255),
OUT Param2 VARCHAR(255),
OUT Param3 VARCHAR(255)
)
BEGIN
DECLARE myvar TEXT;
SET myvar = (SELECT column1 FROM table1 WHERE column1 =2);
INSERT INTO table1 (column1,column2,column3)
VALUES (myvar,'Malaysia','Asia');
COMMIT;
END$$
DELIMITER ;
I believe that you can do a Create as select: http://dev.mysql.com/doc/refman/5.7/en/create-table-select.html
Returning malassia and asia as fixed values for your query...

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 cursor not working with Stored Procedure

I wrote store procedure in mysql. Step were followed this website http://www.mysqltutorial.org/mysql-cursor/
But it doesn't work. Here is code
DELIMITER $$
USE `hr`$$
DROP PROCEDURE IF EXISTS `at_getShift`$$
CREATE DEFINER=`root`#`%` PROCEDURE `at_getShift`()
BEGIN
DECLARE finished BOOLEAN DEFAULT FALSE;
DECLARE employeeID VARCHAR(255);-- Default "";
-- declare cursor for employee email
DECLARE hrEmployee CURSOR FOR SELECT EmployeeID FROM h_employees WHERE EmployeeID IN ('100013', '100014');
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;
DROP TABLE IF EXISTS temp;
CREATE TABLE IF NOT EXISTS temp(
`Code` VARCHAR(255)
);
OPEN hrEmployee;
get_employee: LOOP
FETCH hrEmployee INTO employeeID;
INSERT INTO temp(`Code`) VALUE (employeeID);
-- If no any row, leave loop
IF finished THEN
INSERT INTO temp(`Code`) VALUE ("112");
CLOSE hrEmployee;
LEAVE get_employee;
END IF;
-- insert temp
INSERT INTO temp(`Code`) VALUE ("111");
END LOOP get_employee;
SELECT * FROM temp;
END$$
DELIMITER ;
Execute: CALL at_getShift();
Result is:
2 rows in temp table ( 1 null, 1 is 112)
Please kindly help me to resolve this trouble.
In a SQL statement in MySQL stored program, the references to procedure variables take precedence over references to columns.
That is, when an identifier in a SQL statement matches a procedure variable, the SQL statement references the procedure variable.
References that are qualified with the table name or table alias reference columns from the table, even when there is a procedure variable with the same name.
Demonstration:
CREATE TABLE emp (id INT);
INSERT INTO emp (id) VALUES (101),(102);
DELIMITER $$
CREATE PROCEDURE foo()
BEGIN
DECLARE id INT DEFAULT 3;
-- this query returns 3 for all rows in emp
-- because "id" is a reference to the procedure variable
SELECT id FROM emp WHERE id = 3;
-- this query returns no rows
-- because "id" is a reference to the procedure variable
SELECT id FROM emp WHERE id = 101;
-- this query references columns in the table because
-- references to "id" are qualified
SELECT t.id FROM emp t WHERE t.id = 101;
END$$
DELIMITER ;
CALL foo;
The first query returns value of procedure variable for all rows from emp
id
-----
3
3
second query returns no rows
id
-----
third query returns references "id" column in table:
id
-----
101
The takeaway are two "best practices":
qualify all column references in a SQL statement in a procedure
and
procedure variable names should differ from names of columns, the usual pattern is to use a distinctive prefix on variables. As a trivial example: v_id, v_name, etc.
Both of these practices make it easier for a human reader to decipher a procedure.
Distinctive naming of procedure variables does reduce the chances of collisions, but does not invalidate the "best practice" of qualifying all column references in SQL statements. Both of those serve to make the author's intent more clear to the human reader.
EDIT:
I attempted to answer the question I thought you were asking... "Why is my procedure not doing what I expect it to?".
Beyond the answer to the question you asked... the operation that your procedure appears to be performing (populating a temporary table with a set of rows) that operation could be performed much faster and more efficiently by processing the rows as a set, rather than issuing painfully inefficient individual insert statements for each row. In terms of performance, a cursor loop processing RBAR (row-by-agonizing-row) is going to eat your lunch. And your lunch box.
DELIMITER $$
CREATE PROCEDURE `at_getShift_faster`()
BEGIN
-- ignore warning message when dropping a table that does not exist
DECLARE CONTINUE HANDLER FOR 1305 BEGIN END;
DROP TABLE IF EXISTS temp;
CREATE TABLE IF NOT EXISTS temp(`Code` VARCHAR(255));
INSERT INTO temp (`Code`)
SELECT h.EmployeeID
FROM h_employees h
WHERE h.EmployeeID IN ('100013', '100014')
;
SELECT * FROM temp;
END$$
DELIMITER ;

MySQL: count number of rows returned by a procedure

I want to Insert the records returned by procedure in to temporary table in another procedure
I have a Procedure Like Below
call getName()
Now I want to Check whether the above procedure is returning records or not.
I want to do this in another procedure. So I am trying to insert the records returned from getName() procedure in to temp table in another procedure to carry out count operation.
Let me know how to count no of rows returned by one procedure in another procedure.
Could you let me know how to insert values into temp table from stored procedure in Mysql
create temporary table <name> select * from <some results>
Let me know how to count no of rows returned by one procedure in another procedure.
select count(*) from <name>

how to call multiple columns in a stored procedure

I'm new to stored procedure and I don't know much.
I'm testing with an example. Could you help me?
Here is my stored procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS dictionarytable$$
CREATE PROCEDURE dictionarytable(id VARCHAR(20),name
VARCHAR(20),work VARCHAR(20),place VARCHAR(20),mobileno
VARCHAR(20),bike VARCHAR(20),car VARCHAR(20),homeno
VARCHAR(20),dictionaytype VARCHAR(20),meaning VARCHAR(20),sentence
VARCHAR(20),antonym VARCHAR(20),synonym VARCHAR(20))
BEGIN
select
id,name,work,place,mobileno,bike,car,homeno,dictionaytype,meaning,sentence,antonym,synonym
from dictionary INTO dictionarytable; END $$
DELIMITER ;
I wanted id,name,13 columns from dictionary(table) to be called in stored procedure dictionarytable
the query in the Begin is wrong could you specify a query to display all 13 columns
You cannot pass field values INTO the procedure, you can pass them INTO user variables, declared variables or OUT paramaters. Note, that only one record can be passed when INTO clause is used. For example:
SET #var1 = NULL;
SELECT column1 INTO #var1 FROM table;
If you want to copy more then one record, then you can use INSERT INTO...SELECT statement to copy data-set to second table. For example:
INSERT INTO table2 SELECT column1 FROM table;
Also, if you want to use variables or parameters as identifiers (field names in your case), then you should use prepared statements.