I have string like this " This is a hello world example"

Now I want first two words of the sentence as my output in SQL Server. i.e. This is .

Another example: Original sentence : "Complete word exercise" Output: Complete word

Many solutions will break for any strings that have less than 2 words, which is increasingly likely for people hoping to parse the first n number of words.

Let's first look at the query, and then how we can tell if it actually evaluated correctly.
For that, we need to nest multiple CHARINDEX statements, which take the following params:

<!-- language: lang-sql --> <pre><code>CHARINDEX( <i>expressionToFind</i> , <i>expressionToSearch</i> [ , <i>start_location</i> ] ) </code></pre>

Charindex will return the first index where it finds the specific string. What we keep doing is kicking the ball down the road by adding in a start_location equal to the first found instance +1 so it'll find the 2nd, 3rd, 4th instance, etc. Also, instead of SUBSTRING(@str, 0,... we can just use LEFT(@str,... to capture the first portion of the string, but calculating how far deep to go is the hard part anyway:

<!-- language: lang-sql -->
DECLARE @string VARCHAR(1000) = 'One Two Three';
SELECT LEFT(@string, CHARINDEX(' ', @string,
                     CHARINDEX(' ', @string,
                     CHARINDEX(' ', @string,
                     CHARINDEX(' ', @string)+1)+1)+1))

But this will fail if we don't have the minimum number of words:
<sup>Technically, it'll just keep looping around infinitely. Once it runs out of spaces, it'll start indexing again from the beginning</sup>

Char Index Demo

Pop quiz... what will the above query resolve to? <sub>Hover below for answer</sub>

! SELECT LEFT('One Two Three', 3) -- 'One'

In the solution in Extracting a specific number of words from a string in sql, we can check that the last CHARINDEX produced a non-zero value, meaning it hit a space at that level of depth. But also, since the nested charindex is kind of unwieldy, we can get at that information at little more directly by counting the number of occurrences of a certain substring in a SQL varchar?

So the final solution should look like this to grab the first 4 words:

<!-- language: lang-sql -->
DECLARE @string VARCHAR(1000) = 'One Two Three Four Five Six';

SELECT CASE WHEN LEN(@string)-LEN(REPLACE(@string, ' ', '')) < 4 
			THEN @string
			ELSE LEFT(@string, CHARINDEX(' ', @string,
                               CHARINDEX(' ', @string,
                               CHARINDEX(' ', @string,
                               CHARINDEX(' ', @string)+1)+1)+1))
	   END

If there are less than 4 spaces, we'll just return the whole string. For more than four, we'll find the position of the 4th space and return the left portion of the string all the way to that position