call spQuery_Lista_Cliente_LP(2, 12,null, null);

DROP PROCEDURE IF EXISTS spQuery_Lista_Cliente_LP;
CREATE PROCEDURE spQuery_Lista_Cliente_LP(	
	varEmpresa    int,
  varCodigo     int,
  varNombre     varchar(50),
  varDireccion  varchar(50)
)
BEGIN 
  declare varCadEmp, varCadCod, varCadNom, varCadDir text default '';
  
  if varEmpresa is not null then
    set varCadEmp = concat(" and CL.id_empresa = ", varEmpresa, " ");
  end if;
  if varCodigo is not null then
    set varCadCod = concat(" and CL.id_cliente = ", varCodigo, " ");
  end if;
  if IFNULL(varNombre,'') <> '' then
    set varCadNom = concat(" and C.nombre like '%", varNombre, "%' ");
  end if;
  if IFNULL(varDireccion,'') <> '' then
    set varCadDir = concat(" and C.direccion like '", varDireccion, "' ");
  end if;
  
  set @sql = CONCAT("select CL.id_cliente as CCLI, C.nombre as CLIENTE, C.DIRECCION, C.DNI, C.RUC, ",
                    "C.id_ruta AS CRUT, R.nombre AS RUTA, ",
                    "CL.id_lista AS CLIS, L.nombre AS LISTA, L.monto_minimo AS MMIN ",
                    "from _sv_cliente_lista CL ",
                    "inner join _sv_cliente C ON CL.id_cliente = C.id_cliente ",
                    "inner join _sv_ruta R ON C.id_ruta = R.id_ruta ",
                    "inner join _sv_lista L ON CL.id_empresa = L.id_empresa AND CL.id_lista = L.id_lista ",
                    "where CL._estado = 'A'and C._estado ='A' ",
                    varCadCod, varCadNom, varCadDir, varCadEmp);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;