Skip to content
Advertisement

How can I retrieve first second and third word of a String in SQL?

I need a query which would extract the first second and third word of a string.

I have approximately 5 words in each row and I need only the first three words out of 5 in the same row (1 row). Example “ATV BDSG 232 continue with other words”.

I need only the first three words together in one row (in the same row) like “ATV BDSG 232” as a first row. The table has about 1000 rows and at the end of it I should have 1000 rows again but each row should contain only the first three words of the string.

I found a query which works fine for extracting first two like “ATV BDSG” discussed in stack overflow. The query is

“SELECT SUBSTRING(field1, 0, CHARINDEX(‘ ‘, field1, CHARINDEX(‘ ‘, field1, 0)+1)) FROM Table”

Can we derive this for extracting first three words?

Thanks in advance

Advertisement

Answer

If you don’t want to create a dedicated function, you can use successive CROSS APPLYs:

gives you the results you need:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement