p.s. There are several very good index rebuild scripts already written and available for use. Don't reinvent the wheel.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability