MS SQL: Create User Function to Remove Long Words

I want a user function that will remove all words longer than 7 characters.

For example:
Select dbo.RemoveLongWords('Hello Supercalifragilisticexpialidocious 01234567890 World 123 @#$!@# pneumonoultramicroscopicsilicovolcanoconiosis')

Open in new window

Should return:

Hello World 123 @#$!@#

ALTER Function [dbo].[RemoveLongWords](@Temp NVarChar(MAX))
Returns NVarChar(MAX)
AS
Begin

...???...

End

Open in new window

LVL 10
skijAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

chaauCommented:
Is it a homework?
0
skijAuthor Commented:
@chaau: I've been working longer than you have been living :-)  It is not homework.
0
chaauCommented:
I don't care, in fact, I don't care at all. Good luck with your life with such attitude
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
you may customize:

ALTER Function [dbo].[RemoveLongWords](@Temp NVarChar(MAX))
Returns NVarChar(MAX)
AS
Begin

Declare @separator varchar(2) = ' ';
Declare @v NVarChar(MAX);

with tokens(p, a, b) AS (
    select 
        cast(1 as bigint), 
        cast(1 as bigint), 
        charindex(@separator, @Temp)
    union all
    select
        p + 1, 
        b + 1, 
        charindex(@separator, @Temp, b + 1)
    from tokens
    where b > 0
)
Select 
@v = Stuff(  
(
	Select ' ' + item from 
	(
		select
			p-1 ItemIndex,
			substring(
				@Temp, 
				a, 
				case when b > 0 then b-a ELSE LEN(@Temp) end) 
			AS Item
		from tokens
	) a
	where len(item) <= 7
	For XML PATH ('')
), 1, 1, '')

return @v

End

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
skijAuthor Commented:
This works perfectly, thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.