Thanks guys, I just read an excellent article on CTE that solved my problem.
here is the link
http://www.sqlservercentral.com/articles/T-SQL/62159/
Thanks for posting code too. i just finished my code that is similar to yours.
SQL ServerCentral.com rolls