SQL 2005 T-SQL

Posted on 2012-08-28
Last Modified: 2012-08-29
I would like to use T-sql to flip a string.

I would like to flip 'green,blue'  to 'blue,green'

i wish to flip the order of two words that are separated by a comma.
Question by:dastaub
    LVL 74

    Accepted Solution


    SELECT SUBSTRING(theString, CHARINDEX(',', theString) + 1) + ',' + SUBSTRING(theString, 1, CHARINDEX(',', theString) - 1)

    Open in new window

    LVL 9

    Assisted Solution

    try this

    DECLARE @String VARCHAR(200),
    @indx int, -- Index of the ,
    @tlen int -- Total length of the input

    SET @String = 'green, blue'  
    --SET @String = REPLACE(@String,' ','') -- Remove the spaces
    SELECT @tlen = LEN(@String)
    SELECT @indx = CHARINDEX(',', @String)
    SELECT SUBSTRING(@String,@indx+1,@tlen)+', '+ SUBSTRING(@String,1,@indx-1)

    Author Comment

    below is what worked.

    declare @TotalBy as varchar(max)
    set @TotalBy = '1FacNNNNNNNNo1,1PDDDDDDoc1'
    set @TotalBy = right(@TotalBy,(   len(@TotalBy) - CHARINDEX ( ',' ,@TotalBy))   ) + ',' + left(@TotalBy,CHARINDEX ( ',' ,@TotalBy)-1)
    select @TotalBy

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Suggested Solutions

    Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
    Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
    Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
    Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now