Oh yawn. Not another stab at re-indexing. Don't want put it down as an issue, but there is some really good free index defragmenter code out there already. I'd download those first, and have a look at how they work.
Here's some tips to take those others a step further:
1. Take a look at Ola Hallengren's maintenance routines before even thinking of using this code. It does index maintenance as well as backups and various other functions. It has more code and ideas than this example.
2. Only sample on a handful of indexes per database each night (or whatever your window is) using the physical stats DMF. Otherwise you can end up using a heck of a lot of resource doing that, and doing very little defragmenting.
3. Particularly if you have multi-column clustered indexes, you will want to occasionally do a deeper sample than the usual 'LIMITED' mode for the DMF, possibly even 'DETAILED' (usually 'SAMPLED' is good enough). That might reveal, for instance, an index that has little logical fragmentation, but gone to 4 levels deep, yet has very little in the 3rd level. On a rebuild (online) we're back to just 2 index levels.
4. As Paul Randall says, his 30% guideline was just made up on the fly. It's probably not a bad one, just something to bear in mind - you might want to analyse over the longer term. You might want to tweak those levels, for example we're more biased towards defrags than re-builds - especially for massive tables. We tend use repeated defrags, to incrementally chip away at any major problems. Otherwise if it recrurs over a long time you might want to consider other options, such as altering the fillfactor and / or take other action.
5. Put in logging of what happens to your index defragmentation (/ rebuild) process: does it fail (deadlock, timeout, other), how long did it take, when did you last do it. Then you can build a self-administering / tuning system that can adjust it's own parameters.
6. Check and update your statistics after you've done the re-indexing work.
We've built on all those ideas, and more, and come up with what we call a site-wide self-tuning re-indexer. Sorry it's not published, but above is the seed corn ideas, and a better example starting point, if you want to do something similar.
This DBA says - "It depends".