The present invention discloses novel piperidine and pyrrolidine derivatives having NPY Y5 receptor antagonistic activity. Specifically, the present invention discloses a compound represented by the formula (I), a pharmaceutically acceptable salt or a solvate thereof:whereinA is substituted or unsubstituted monocyclic aryl or monocyclic heterocyclyl; X is a single bond or C(=O); Y is a single bond, CR5R6NR7 or C (=O) NR7; R1 and R2 are independently hydrogen or substituted or unsubstituted alkyl; R3 is substituted or unsubstituted aryl or heterocyclyl; R4 is halogen, substituted or unsubstituted alkyl, alkoxy, aryloxy or heterocyclyloxy, etc.; p is an integer of 0 to 2; q is 0 or 1; m is 0 or 1; n is an integer of 0 to 5; and B is aromatic carbocycle, monocyclic heterocycle or bicyclic fused hetero ring.