sys.all_columns is a thing called a view, sort of a virtual table that is defined by a SELECT statement. It’s just a list of all the columns in the database. I regret using it and suggest you lose that version of generating the tally table. It’s information you’ll never need unless you become a DBA someday.
The format for the SUBSTRING function is:
SUBSTRING ( expression ,start , length ) – See the technet description at http://technet.microsoft.com/en-us/library/ms187748.aspx
The format for the CHARINDEX function is:
CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] ) – http://technet.microsoft.com/en-us/library/ms186323.aspx
Let’s say you have a table named “S_TABLE” and a varchar column named “VARCHAR_COL”. The query would then be:
select substring(VARCHAR_COL, bob, charindex(' ', VARCHAR_COL + ' ', bob) - bob) as word
into #temptable
from #tally, S_TABLE
where bob <= convert(int, len(VARCHAR_COL))
and substring(' ' + VARCHAR_COL, bob, 1) = ' '
In the first line, CHARINDEX is used to find the next blank space in VARCHAR_COL starting at bob. If it finds the first blank space at position 5, then that’s the value of bob that it uses. Next in SUBSTRING, it takes the part of the string starting at bob = 1 because SUBSTRING doesn’t know anything about what CHARINDEX is doing, only what it’s returning. So what we end up with is:
select substring(VARCHAR_COL, 1, charindex(' ', VARCHAR_COL + ' ', 1) - 1) as word
or using the value that CHARINDEX returns:
select substring(VARCHAR_COL, 1, 5 - 1) as word
That means that the first substring is the first 4 characters of the string, but it also does this for the next iteration of bob which is 6. It will continue to do this for the entire string as long as the conditions in the WHERE clause are being met. And it isn’t just doing that for the one string, it’s doing it for every value of VARCHAR_COL in the entire table. You can see how bob is being used by running this version of the query:
select bob, substring(VARCHAR_COL, bob, charindex(' ', VARCHAR_COL + ' ', bob) - bob) as word
from #tally, S_TABLE
where bob <= convert(int, len(VARCHAR_COL))
and substring(' ' + VARCHAR_COL, bob, 1) = ' '
I hope that clears things up. If you play with SUBSTRING and CHARINDEX separately, it will help you understand how they work together.
BTW, I hope everyone realizes by this time that there are no stupid questions where SQL is concerned and it’s impossible to show your ignorance about it. Can I get an Amen?