TSQL help on strings

  • Hi All,

    I have a table with a varchar column. My requirment is to remove all the extra blank spaces between the words in each string.
    Can anyone help.

    Example.

    create table t1
    ( c1 varchar(5000)
    )
    go
    insert into t1
    select 'Hello  world '
    union all
    select '  Welcome to  the universe  '
    union all
    select ' This is  sample test    string'
    go

    Expected output should be like this.
    select c1 from t1;

    Hello world
    Welcome to the universe
    This is sample test string

    Thanks,

    Sam

  • Have a look at rtrim and ltrim, or just trim if you're on SQL 2017.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Actually, I think that the solution is something as the one presented here:
    http://www.sqlservercentral.com/articles/T-SQL/68378/

    Be sure to follow the links for the optimal solutions.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Thanks a lot Luis and Thom for the suggestions.

  • Luis Cazares - Friday, October 13, 2017 1:49 PM

    Actually, I think that the solution is something as the one presented here:
    http://www.sqlservercentral.com/articles/T-SQL/68378/

    Be sure to follow the links for the optimal solutions.

    You might be right there Luis. Difficult to tell when the OP might have posted large amounts of white space outside code IF markup. :hehe:

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Luis Cazares - Friday, October 13, 2017 1:49 PM

    Actually, I think that the solution is something as the one presented here:
    http://www.sqlservercentral.com/articles/T-SQL/68378/

    Be sure to follow the links for the optimal solutions.

    Exactly.  Those links are in the "Prologue" of the article and are much faster than the one in the article.  The discussion was an awesome demonstration of what this community can do when we get together.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

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

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