You can use the query below:
DECLARE @Sentence VARCHAR(MAX) = 'The quick brown fox jumps over the lazy dog' DECLARE @first_space_index int = CHARINDEX(' ', @Sentence) - 1 DECLARE @last_space_index int = CHARINDEX(' ', REVERSE(@Sentence)) - 1 IF @first_space_index < 0 SELECT @Sentence AS [First Word], @Sentence AS [Last Word] ELSE SELECT SUBSTRING(@Sentence, 1, @first_space_index) AS [First Word], REVERSE(SUBSTRING(REVERSE(@Sentence), 1, @last_space_index)) AS [Last Word] First Word Last Word ------------ ----------- The dog If @Sentence = 'The' then the result will be: First Word Last Word ------------ ----------- The The
Fails if only 1 word
Thanks for the feedback, Daniel. I have updated the solution. 🙂