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

How can we use a MySQL stored function in a database query?


It can be understood with the help of following the example in which we have created a function ‘Profit’ to calculate the profit and apply that function on the data of table ‘item_list’ by using it in the database query.

Example

mysql> CREATE FUNCTION profit(Cost DECIMAL (10,2),Price DECIMAL(10,2))
    -> RETURNS DECIMAL(10,2)
    -> BEGIN
    -> DECLARE profit DECIMAL(10,2);
    -> SET profit = price - cost;
    -> RETURN profit;
    -> END //
Query OK, 0 rows affected (0.07 sec)

mysql> Select * from item_list;
+-----------+-------+-------+
| Item_name | Price | Cost  |
+-----------+-------+-------+
| Notebook  | 24.50 | 20.50 |
| Pencilbox | 78.50 | 75.70 |
| Pen       | 26.80 | 19.70 |
+-----------+-------+-------+
3 rows in set (0.00 sec)

The above query shows the data from table item_list. Now use the function ‘profit’, created above, in the database query as follows −

mysql> Select *, profit(cost, price) AS Profit from item_list;
+-----------+-------+-------+--------+
| Item_name | Price | Cost | Profit |
+-----------+-------+-------+--------+
| Notebook  | 24.50 | 20.50 |   4.00 |
| Pencilbox | 78.50 | 75.70 |   2.80 |
| Pen       | 26.80 | 19.70 |   7.10 |
+-----------+-------+-------+--------+
3 rows in set (0.00 sec)