I want to limit a string field length in MYSQL on a certain length, but I don't want any chopping up of words to occur.
When I do:
SELECT SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 28)
I get this as output:
Business Analist met focus o
But I would like
Business Analist met focus
How can I enforce a limit of 28 chars, but prevent chopping up words? Off course it's easy in [insert programming language of choice here] ;-), but I want to know if it's possible in MYSQL in a simple statement.
Simple function:
Use:
Let
@str
be your string and@len
the initial position to cut at. Then the necessary steps could be:Take the leftmost
@len
characters of@str
.Reverse the substring.
Find the position of the first space in the reversed substring.
Subtract
1
from the position. But if no space was found, let the position remain0
.Subtract the found position from
@len
and call itcutpos
.Take the first (leftmost)
cutpos
characters of@str
asstr1
, take all the other characters (starting fromcutpos+1
) asstr2
.What about splitting on spaces :
will return
Seems like people don't read the mysql manual:
Original:
SELECT SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 28)
gives broken words.Modified:
SELECT SUBSTRING_INDEX('Business Analist met focus op wet- en regelgeving', ' ' , 4)
gives unbroken wordsSUBSTRING_INDEX(string, delimiter, number)
will truncate a string by the number of times delimiter is found. Make your delimiter a space and you will get whole words only. so:SUBSTRING_INDEX( LEFT('Business Analist met focus op wet- en regelgeving',28), ' ' , 4)
should do it.Very interesting problem. Here's how I did it:
In SQL it would be...
I dont know if all these functions are available in MYSQL
EDIT: I think for MYSQL substitute "Locate" for "CharIndex"