Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first word of a string in a SQL Server query

Tags:

tsql

What's the best way to extract the first word of a string in sql server query?

like image 996
holiveira Avatar asked Apr 01 '09 22:04

holiveira


People also ask

How do I select the first word in SQL?

To select first word in MySQL query, you can use SUBSTRING_INDEX().

How do I remove the first word from a string in SQL Server?

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()".


2 Answers

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') 
like image 109
Marc Gravell Avatar answered Nov 12 '22 12:11

Marc Gravell


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.

like image 45
Ben Brandt Avatar answered Nov 12 '22 14:11

Ben Brandt