String Manupulation

  • Hello Everyone,

    How can i read the first 5 characters in a string by excluding spaces.

    Eg:  AAA LOGISTICS  ,BB LOGISTICS, CCLOGISTICS

    Output should be:

    AAALO

    BBLOG

    CCLOG

    I have tried using LTRIM, LEFT, CHARINDEX but not achieved output. Some please help me on this.

     

    Thanks.

     

  • Replace the spaces first, then read the first 5 characters of the replaced string ...

    LEFT(REPLACE())

    The absence of evidence is not evidence of absence.
    Martin Rees

    You can lead a horse to water, but a pencil must be lead.
    Stan Laurel

  • Hey Guru,

    Could you please eloborate .

  • Here's a code sample which demonstrates the technique:

    DECLARE @SomeText VARCHAR(50) = '1 2 3 4    5 blah blah';

    SELECT @SomeText
    ,LEFT(REPLACE(@SomeText, ' ', ''), 5);

    The absence of evidence is not evidence of absence.
    Martin Rees

    You can lead a horse to water, but a pencil must be lead.
    Stan Laurel

  • You also could simply look up the functions in Microsofts online documentation.

     

  • Here is the sample code.

    DECLARE @var VARCHAR(100) ='CCLOGISTICS'

    SELECT @var

    ,  CASE WHEN CHARINDEX(' ',@var)>0 THEN SUBSTRING(REPLACE(@var,' ',''),1,5) ELSE SUBSTRING(@var,1,5) END AS substringoutput

     

    Let me know for further questions.

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply