BDM connected or not connected often suggests that the problem might be related to "write-once" registers. These registers are found here and there in the various peripherals of the S12, and their nature is such that they can only be written to once in normal single chip mode. In special single chip mode, that is when the BDM is connected, you can write to them several times.
Which registers that are write-once is poorly documented, basically you will have to read through the whole manual page by page to find them. To save you from that pain, here is a list of write-once registers in the S12 D family. S12X or other S12 derivates may have additional ones.
000A PEAR
000B MODE
000E EBICTL
0010 INITRM
0011 INITRG
0012 INITEE
0013 MISC
001E INTCR
0039 CLKSEL
003C COPCTL
00E8 DLCBCR1
00EC DLCBARD
00ED DLCBRSR
0100 FCLKDIV
0110 ECLKDIV
0141 CAN0CTL1
0181 CAN1CTL1
01C1 CAN2CTL1
0201 CAN3CTL1
0281 CAN4CTL1
For example, you could perhaps have code for your bootloader, writing to the FCLKDIV register like this:
FCLKDIV = some_calculated_value;
FCLKDIV |= PRDIV8; /* will work with BDM connected, otherwise not = flash prescaler clock will go haywire */
This seems to be a somewhat common bug on S12 devices, and it is incredibly hard to find.
---
Other causes apart from this could be something related to your BKGD and reset pin circuitry, but that is less likely.
Also make sure that you aren't writing to a flash page from a routine executed in the same flash page: this doesn't work, although when single-stepping through such code with a BDM, it might -seem- to work.