What's the best way to extract the first word of a string in sql server query?
To select first word in MySQL query, you can use SUBSTRING_INDEX().
Use SUBSTRING() with LOCATE() , if you consider a "word" to be bound by a single space character. LOCATE() will return the position of the first occurrence of its first argument. Absolutely correct: for mySql, use "substring()" with "locate()".
SELECT CASE CHARINDEX(' ', @Foo, 1) WHEN 0 THEN @Foo -- empty or single word ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word END
You could perhaps use this in a UDF:
CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max)) RETURNS varchar(max) AS BEGIN RETURN CASE CHARINDEX(' ', @value, 1) WHEN 0 THEN @value ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END END GO -- test: SELECT dbo.FirstWord(NULL) SELECT dbo.FirstWord('') SELECT dbo.FirstWord('abc') SELECT dbo.FirstWord('abc def') SELECT dbo.FirstWord('abc def ghi')
I wanted to do something like this without making a separate function, and came up with this simple one-line approach:
DECLARE @test NVARCHAR(255) SET @test = 'First Second' SELECT SUBSTRING(@test,1,(CHARINDEX(' ',@test + ' ')-1))
This would return the result "First"
It's short, just not as robust, as it assumes your string doesn't start with a space. It will handle one-word inputs, multi-word inputs, and empty string or NULL inputs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With