0

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..

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.