You can try this.
;with T1 as(
select CustomerName,
stuff(reverse(stuff(reverse(CustomerName),1,len(lastname) + 1, '')),1,len(firstname) + 1, '') as middle
from (select CustomerName,
left(CustomerName, charindex(' ', CustomerName) - 1) as firstname,
right(CustomerName, charindex(' ', reverse(CustomerName)) - 1) as lastname
FROM [dbo].[CustomerData]) c
),T2 as (
select CustomerName,trim(middle) as middle from T1)
select case when middle = '' then LEN(CustomerName)-LEN(REPLACE(CustomerName, ' ', ''))
else charindex(middle,CustomerName) - charindex(' ',CustomerName) end as spacecount from T2;
Output:
Best regards,
Percy Tang
If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.