Creating a stored procedure

Let's learn how to create a stored procedure. First, we'll go through the following syntax, which is used to create a stored procedure: 

DELIMITER $$
CREATE PROCEDURE storedprocname()
BEGIN
your sql statments go here;
END $$
DELIMITER ;

In the previous code sample, we have the following:

  • DELIMITER lets MySQL know that there may be lines in-between the delimiter statements that end in a semicolon. 
  • If you don't put DELIMITER around a stored procedure, you will get an error when MySQL hits the semicolon in your first SQL query, inside the stored procedure.

Let's work through an example of how to create a stored procedure. The following code will help you create a stored procedure:

USE lahmansbaseballdb;
DELIMITER $$
CREATE PROCEDURE getplayergameinfo()
BEGIN
SELECT p.playerid, birthyear, a.yearid,
a.teamid, G_defense AS defensegames,
H AS numberofhits
FROM appearances AS a
JOIN people AS p ON p.playerid = a.playerid
JOIN batting AS b ON a.playerid = b.playerid
AND a.yearid = b.yearid
AND a.teamid = b.teamid
WHERE b.yearid = 2017 AND H <> 0
ORDER BY p.playerid, a.yearid, a.teamid,
G_defense, H;
END $$
DELIMITER ;

With that, you have created a stored procedure.

In order to call the stored procedure that you just created, execute the following code: 

USE lahmansbaseballdb;
CALL getplayergameinfo();

The call to the stored procedure will return the results shown in the following screenshot:

You can view the stored procedures that were created in MySQL Workbench in the SCHEMAS panel for each database, right below the Views listing:

If you don't see the stored procedure you just created listed under Stored Procedures, then right-click Stored Procedures and choose Refresh All

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.75.133