call spQuery_DevengeRegimen(NULL,NULL,NULL,NULL);

DROP PROCEDURE IF EXISTS spQuery_DevengeRegimen;
CREATE PROCEDURE spQuery_DevengeRegimen(
  varRegimen  varchar(2),
  varPeriodo  int,
  varField    varchar(60),
  varOrder    varchar(5)
  )
BEGIN
  DECLARE varCadReg, varCadPer  text default '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  if varRegimen is not null or varRegimen <> '' then
    set varCadReg = CONCAT(" and D.id_regimen = '", varRegimen, "' ");
  end if;
  if ifnull(varPeriodo,'') <> '' then
    set varCadPer = CONCAT(" and D.id_periodo_afp = ", varPeriodo, " ");
  end if;
  
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'D._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'D._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;

	set @sql = CONCAT("select D.id_periodo_afp as CPER, P.nombre as PERIODO, ",
                    "D.id_regimen as CREG, R.nombre as REGIMEN, ",
                    "D.porc_comision as COMISION, D.porc_prima as PRIMA, D.porc_fondo as FONDO ",
                    "from _srh_devenge_regimen D ",
                    "inner join _srh_periodo_afp P ON D.id_periodo_afp = P.id_periodo_afp ",
                    "inner join _srh_regimen_pension R ON D.id_regimen = R.id_regimen ",
                    "left join _sys_usuario UN ON D._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON D._user_update = UU.id_usuario ",
                    "where D._estado='A' ",
	                  varCadReg, varCadPer,
                    varCadOrd);		
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;                    