What is a stored procedure, and how is it different from a function?
MediumConceptDBMS Fundamentals
Answer
A stored procedure is a named set of SQL statements saved inside the database and run with a single call, such as CALL give_raise(10). It can take parameters, use logic such as IF and loops, and run several statements as one unit.
- Benefits: less network traffic (one call instead of many statements), reusable logic, and permission can be granted on the procedure instead of on the tables.
- A function must return a value and can be used inside a query, as in
SELECT tax(price) FROM items. A procedure is called on its own and returns results through output parameters or result sets. - Procedures can usually control transactions with
COMMITandROLLBACK; functions cannot, and SQL Server does not allow a function to modify tables at all.
Example: In MySQL:
CREATE PROCEDURE give_raise(IN pct INT)
UPDATE employees SET salary = salary * (1 + pct / 100);
CALL give_raise(10); -- every salary rises by 10 percent