Alphabetizing Words in a Phrase Using SQL


I had the need to today to alphabetize a phrase using SQL. For example, I needed “red cowboy pretty hat” to read “cowboy hat pretty red”. Here is the code I wrote to do so:

declare @input varchar(100)

set @input = "red cowboy pretty hat"

--declarations
DECLARE @i            int
        ,@len        int
        ,@word        varchar(100)
        ,@char        varchar(1)
        ,@newphrase    varchar(1000)

--Variable/Constant initializations
SET @i = 1
SET @len = LEN(@input)
SET @word = ""
SET @newphrase = ""

create table #temp(word varchar(100))

WHILE @i < @len
  begin

    SET @char = SUBSTRING(@input, @i, 1)
    IF @char = " "
      begin
            --add word to temp table
            if len(@word) > 0
                insert into #temp(word)
                select @word

            SET @word = ""
      end
    else
        SET @word = @word + @char

    SET @i = @i + 1
  end

select @newphrase = @newphrase + " " + word
from #temp
order by word

print @newphrase

drop table #temp

Leave a Reply

Your email address will not be published. Required fields are marked *