Here's a way to do step 1 with executeSQLQuery:
select device.name from device,numplan,devicenumplanmap,callforwarddynamic
where numplan.dnorpattern = "<the dn>" and
callforwarddynamic.cfadestination is not null and
callforwarddynamic.cfavoicemailenabled = "t" and
devicenumplanmap.fknumplan=numplan.pkid and
callforwarddynamic.fknumplan=numplan.pkid and
devicenumplanmap.fkdevice=device.pkid
Unless I'm misunderstanding your goals, the rest should be pretty straightforward, I think.
Some people prefer:
where numplan.dnorpattern like "<the dn>" and