• Since some of us do not necessarily have a similar environment as you, it may be helpful if you created temporary tables and populated it with data from your msdb database for us to work with.

    A little hard to work on your code with no data to test against. Won't know if what we did was what you are actually trying to accomplish.

    From your own signature block:

    For better, quicker answers on T-SQL questions, click on the following...

    http://www.sqlservercentral.com/articles/Best+Practices/61537/