String truncate on length, but no chopping up of words allowed

后端 未结 8 1685
旧巷少年郎
旧巷少年郎 2020-12-15 19:33

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(         


        
相关标签:
8条回答
  • 2020-12-15 20:20

    Very interesting problem. Here's how I did it:

    //gets initial string - use 29 instead of 28 to see if the 29th  character is a space
    SELECT SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29) 
    
    //inverts the string, so we can get the first 
    SELECT REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29))
    
    // find the charindex of the first space (last space in the string not reversed)
    SELECT CHARINDEX(' ', REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29)))
    
    // get the substring from the first (last) space
    SELECT  SUBSTRING(REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29)), CHARINDEX(' ', REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29))), 29)
    
    // reverse the string again to unfold it.
    SELECT REVERSE(SUBSTRING(REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29)), CHARINDEX(' ', REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, 29))), 29))
    
    
    // to try different lengths...
    DECLARE  @size  int
    select @size = 24
    SELECT REVERSE(SUBSTRING(REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, @size)), 
    CHARINDEX(' ', REVERSE( SUBSTRING('Business Analist met focus op wet- en regelgeving', 1, @size))), @size))
    
    0 讨论(0)
  • 2020-12-15 20:23

    In SQL it would be...

    select Substring('Business Analist met focus op wet- en regelgeving', 0 , 28 + 2 - CharIndex(' ',  REVERSE(SUBSTRING('Business Analist met focus op wet- en regelgeving', 0, 28 + 1 )),0))
    

    I dont know if all these functions are available in MYSQL

    EDIT: I think for MYSQL substitute "Locate" for "CharIndex"

    0 讨论(0)
提交回复
热议问题