SQL Server - Extracting All The Words From a String In An SQL Query

Extracting All The Words From a String In A SQL Server Database Query

It is easy enough to extract the first word from a string in a database query, but what if you need to separate all words in a given string into a list of separate words?

This is a job for Common Table Expressions (CTEs) as they enable us to repeatedly read a single record while changing it each time.

Here is a SQL Server example which takes a string variable and spearates it into inidividual words. We use a combination of CHARINDEX, LEFT and RIGHT functions to achieve it.

Common Table Expressions (CTEs) To The Rescue!

I was recently asked by a delegate how they could calculate lost work hours due to sick days on a per month basis. This might sound fairly straight forward, but their database only stored the start date for the sickness period and the number of days for the sickness period. So, that means that if an employee was off sick for a period of 5 days starting October 28th, 3 of the days should be counted into October and 2 of the days should be counted in November. Not so simple after all!