Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

MYSQL STORED ROUTINES

March, 2023
WHAT ARE STORED ROUTINES?

• Stored Procedure • Function


• A way of saving a query or series of queries • A method that can alter and manipulate data
to the database itself • Can accept parameters, and always returns a
• Can accept and pass back values value
• Allows programmatic logic to be used in • Can be called in a SQL query with typical
queries function syntax:
• SELECT custName, addTax(amount)
HOW DO WE USE IT?

• Both follow a similar structure • Stored Procedure


• Define Delimiter symbol (which symbol • Must specify if a parameter is IN, OUT, or INOUT
ends the statement) • Can be executed by:
• Allows multiple ‘;’ in a routine • CALL procedureName()
• SET @var = CALL procedureName()
• Create the routine with your statements
enclosed between BEGIN and END • Function
• Must specify what datatype will be returned, and
have a RETURN statement
• Can be executed anywhere you would reference a
column
WHAT’S THE SYNTAX?

• Stored Procedure • Function


EXAMPLE STORED ROUTINES
• Stored Procedure • Function
LIMITATIONS

• Most of what can be done in a routine can be done with manual SQL statements
• Are best suited for slightly modifying data; not the best choice for implementing complicated
business logic
• Should be used for queries that are run semi-regularly
• Not ideal for daily or more use, as client code is usually more efficient and accurate

• Routines take up space, so the more of them there are, the larger your database needs to be
HOW TO STOP MID-EXECUTION

• Say you run into an error partway through your execution of a procedure, either from logic or
data entered by the user
• Instead of having the procedure crash and fail entirely, or fully stop the server, you can have checks
that will catch the errors/logic and exit the procedure early
• This is done by assigning a label to the procedure with the BEGIN statement
• Can then be exited with the LEAVE labelName; command
LEAVE EXAMPLE

You might also like