Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by space

I am trying to use a result of a string split to where close in my sql condition

I have table which has a varchar column. I am trying to filter the result where there is only one word is presented.

eg. if the table have values like 'ABC DEF','XYZ','EGF HIJ' and I am expecting to get only 'XYZ' as result.

I am not sure what to use here, though splitting the each value in column will be a one way. But not sure how I can use it as a condition

I had look some split samples like below.

DECLARE @Str VARCHAR(100) ='Test Word'

SELECT SUBSTRING(@Str , 1, CHARINDEX(' ', @Str ) - 1) AS [First],
       SUBSTRING(@Str , CHARINDEX(' ', @Str ) + 1, LEN(@Str )) AS [Last]
like image 291
huMpty duMpty Avatar asked Oct 04 '13 14:10

huMpty duMpty


People also ask

How do you split a string by spaces in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split one or more spaces?

split() method to split a string by one or more spaces. The str. split() method splits the string into a list of substrings using a delimiter.

How do I split a space in Javascript?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.


2 Answers

This is also work

select SUBSTRING(EmpName,0,CHARINDEX(' ',EmpName)),SUBSTRING(EmpName,CHARINDEX(' ',EmpName),LEN(EMPNAME)) 
from tblemployee
like image 106
rinku Choudhary Avatar answered Oct 23 '22 02:10

rinku Choudhary


To get only 'XYZ' in the with a column containing

tableName.fieldName
'ABC DEF'
'XYZ'
'EGF HIJ' 

Do this

SELECT * 
FROM tableName
WHERE CHARINDEX(' ',fieldname) = 0
like image 32
Hogan Avatar answered Oct 23 '22 03:10

Hogan