Search code examples
sqlsql-serversql-server-2017

How to split a sentence and get only left 15 or less (Not greater than 15) characters on one column but at the end it could be a complete word


How to split a sentence and get only left 15 or less (Not greater than 15) characters on one column but it could be a complete word.

Example: Ali, House Number ABC/123, Sattelite Town, Lahore.

Column 01           Column 02           Column 03           Column 04
Ali, House          NumberABC/123,      Sattelite Town,     Lahore.

Need support here.


Solution

  • You can try something like this:

    DECLARE @Str VARCHAR(100) = 'Ali, House Number ABC/123, Sattelite Town, Lahore.'
    
    SELECT LEFT(LEFT(@Str, 15) , 15 - CHARINDEX(' ', REVERSE(LEFT(@Str, 15))) )