UDF for longest word in string

A

aaron.kempf

Team;

I've got a string like

'hello world grandma'

and I want to find or write a UDF that will tell me the longest WORD
out of that string (in other words, grandma).. i'm using SQL 2000 of
course :)


-Aaron
 
R

Russ Rose

Looping through the input string either one character at a time or jumping
from space to space using charindex would be the common way to go.

I would be interested in creating a Split function that built a temp table
instead of an array. Then you could use the LEN function to easily find
and/or sort the individual words.

Usage of below function:

SELECT * FROM dbo.Split('In the course of human events', ' ')

This could get the longest word
SELECT TOP 1 value FROM dbo.Split('In the course of human events', ' ')
ORDER BY length desc


CREATE FUNCTION dbo.Split(@str varchar(8000), @delimiter varchar(20) = '
')

RETURNS @T TABLE

( position int IDENTITY PRIMARY KEY,
value varchar(8000) ,
length smallint null
)

AS

BEGIN
DECLARE @i int
SET @i = -1
WHILE (LEN(@str) > 0)
BEGIN
SET @i = CHARINDEX(@delimiter , @str)
IF (@i = 0) AND (LEN(@str) > 0)
BEGIN
INSERT INTO @T (value, length) VALUES (@str, LEN(@str))
BREAK
END
IF (@i > 1)
BEGIN
INSERT INTO @T (value, length) VALUES (LEFT(@str, @i - 1),
LEN(LEFT(@str, @i - 1)))
SET @str = RIGHT(@str, (LEN(@str) - @i))
END
ELSE
SET @str = RIGHT(@str, (LEN(@str) - @i))
END
RETURN
END
 
A

aaron.kempf

yeah I ended up using it in vb; but i'll definitely check that out
thanks!

-Aaron
 
A

Alex Kuznetsov

Aaron,

There is a simple set based solution:

DECLARE @c VARCHAR(70)
SET @c = ' 123 12345 1234567 123456 1234567 123 1234 '
SELECT TOP 1 SUBSTRING(@c, NotBlank, NextBlank)
FROM (
SELECT n.Number NotBlank, CHARINDEX(' ', @c, n.Number + 1) - n.Number
NextBlank FROM dbo.Numbers n
WHERE SUBSTRING(@c, n.Number, 1) <> ' '
) t
ORDER BY NextBlank DESC
 
A

aaron.kempf

yeah I love those recursive way to do things like that.. it seems
pretty darn powerful

now.. i dont want to sound dumb.. but by 'set based' this means it's
not cursor based.. right?

also; is this 2005 specific?

-Aaron
 
A

Alex Kuznetsov

I tested against SQL 2000, works all right. BTW this is not a recursive
query.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top