Create dynamic query in stored procedure MySQL?

I have a bunch of tables that are inner joined and im trying to dynamically add or concat a WHERE clause from IN parameters that may or may not contain value.

PROCEDURE `tablaReporte`(IN IdSeguro int, IN IdTomador int, IN IdAgente int, IN fechaInicio date)
BEGIN
SELECT p.Id_seguro, CONCAT(c.Nombre, ' ', c.Apellido) AS Nombre, CONCAT(a.Nombre, ' ', a.Apellido) AS NombreAgente,
p.fechaInicio, p.fechaFin, p.fechaContratacion, s.TipoSeguro, e.Descripcion
FROM POLIZA P 
INNER JOIN TOMADOR C ON P.Id_tomador = C.IdTomador
INNER JOIN AGENTE A ON P.Id_agente = A.idAgente
INNER JOIN SEGURO S ON P.Id_seguro = S.idSeguro
INNER JOIN ESTADO E ON S.idEstado = E.idEstado
WHERE P.Id_seguro = IdSeguro AND

This is the part where I have to validate if the next parameters have value or not. Something like

IF IdTomador IS NOT NULL
THEN
 CONCAT(' P.Id_tomador = ', IdTomador); //Concat to the initial query
END IF;

And the same with the next parameter..

728x90

1 Answers Create dynamic query in stored procedure MySQL?

Instead of dynamic sql, use a static sql statement that adapts to the fact that the parameter may be null.

So this would always be in the WHERE clause: P.Id_tomador = coalesce(IdTomador, p.id)

The full query would be:

SELECT p.Id_seguro, CONCAT(c.Nombre, ' ', c.Apellido) AS Nombre, CONCAT(a.Nombre, ' ', a.Apellido) AS NombreAgente,
p.fechaInicio, p.fechaFin, p.fechaContratacion, s.TipoSeguro, e.Descripcion
FROM POLIZA P 
INNER JOIN TOMADOR C ON P.Id_tomador = C.IdTomador
INNER JOIN AGENTE A ON P.Id_agente = A.idAgente
INNER JOIN SEGURO S ON P.Id_seguro = S.idSeguro
INNER JOIN ESTADO E ON S.idEstado = E.idEstado
WHERE P.Id_seguro = IdSeguro AND
P.Id_tomador = coalesce(IdTomador, p.id)

4 months ago