Computer >> Computer tutorials >  >> Programming >> MySQL

How can we access tables through MySQL stored procedures?


We can access one or all the tables from the MySQL stored procedure. Following is an example in which we created a stored procedure that will accept the name of the table as a parameter and after invoking it, will produce the result set with all the details from the table.

Example

mysql> Delimiter //
mysql> Create procedure access(tablename varchar(30))
   -> BEGIN
   -> SET @X := CONCAT('Select * from',' ',tablename);
   -> Prepare statement from @X;
   -> Execute statement;
   -> END//
Query OK, 0 rows affected (0.16 sec)

Now invoke the procedure with the table name, we need to access, as its parameter.

mysql> Delimiter ;

mysql> Call access('student_info');
+------+---------+----------+------------+
| id   | Name    | Address  | Subject    |
+------+---------+----------+------------+
| 101  | YashPal | Amritsar | History    |
| 105  | Gaurav  | Jaipur   | Literature |
| 125  | Raman   | Shimla   | Computers  |
+------+---------+----------+------------+
3 rows in set (0.02 sec)
Query OK, 0 rows affected (0.04 sec)