Dynamic query for stored procedure I need query of looping in stored procedure for table like this:

Table Matrix Report

| Nama  | Motor   |
|-------|---------|
| Abdul | Vario   |
| Abdul | Beat    |
| Mei   | Supra   |
| Leli  | Supra   |
| Budi  | Megapro |
| Ali   | CB150   |


Output :

| Nama   | Vario | Beat | Supra | Megapro | CB150 |
|--------|-------|------|-------|---------|-------|
| Abdul  | 1     | 1    | 0     | 0       | 0     |
| Mei    | 0     | 0    | 1     | 0       | 0     |
| Leli   | 0     | 0    | 1     | 0       | 0     |
| Budi   | 0     | 0    | 0     | 1       | 0     |
| Ali    | 0     | 0    | 0     | 0       | 1     |


I need dynamic query because if I added new data, they automatically sum up.
Actually you don't need a dynamic query, you need a pivot query:

SELECT Nama,
SUM(CASE WHEN Motor = 'Vario' THEN 1 ELSE 0 END) as Vario,
SUM(CASE WHEN Motor = 'Beat' THEN 1 ELSE 0 END) as Beat,
SUM(CASE WHEN Motor = 'Supra' THEN 1 ELSE 0 END) as Supra,
SUM(CASE WHEN Motor = 'Megapro' THEN 1 ELSE 0 END) as Megapro
SUM(CASE WHEN Motor = 'CB150' THEN 1 ELSE 0 END) as CB150
FROM MatrixReport
GROUP BY Nama;


This query will automatically sum up whether new rows are added or not.

This is a SQL query, not an SP. You need to learn more about how to create a stored procedure. Take a look at these Stack Overflow Q &amp; As to help you in creating your first SP:


Beginners' guide to stored procedures with MySQL
Creating a Procedure MySQL
MySQL create stored procedure syntax with delimiter


You should also learn more about GROUP_CONCAT function in MySQL:


Aggregate (GROUP BY) Function Descriptions - GROUP_CONCAT
How to use GROUP_CONCAT in a CONCAT in mysql