Link to home
Start Free TrialLog in
Avatar of cheryl9063
cheryl9063Flag for United States of America

asked on

SQL UDF to get last word in string

I got the code below off the internet but the syntax is off.. What is the best way to create a UDF that pulls the last word out of a string?
CREATE FUNCTION dbo.ufn.Utility_Last_Word(@myString VARCHAR(4000) )
 RETURNS VARCHAR(4000)
 
RETURN
WITH find_last_blank(pos) AS (
VALUES LENGTH(@myString)
UNION ALL
SELECT pos - 1
  FROM find_last_blank
 WHERE pos > 0
   AND SUBSTR(in_string, pos, 1) <> ' '
)
SELECT SUBSTR(in_string, MIN(pos) + 1)
  FROM find_last_blank
;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mcv22
mcv22
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cheryl9063

ASKER

Thanks!