SQL how to update a field with sequential number but sorted alphabetically

Hi there,
I would like to update a field in a table with a sequential number. I can do this using:

DECLARE @seqNum int
SET @seqNum = 0
  @seqNum = myAnalysisCode = @seqNum + 1
Where MyAnalysisType = whateverIchoose

This works fine, BUT I want to sort my selection alphabetically before adding the sequential code - eg I have data:
cat toys large                  
dog toys small              
cat toys medium          
hamster wheels            
Dog chews              

I want to add an analysis code so I get
cat toys large                  1
dog toys small                4
cat toys medium             2
hamster wheels            5
Dog chews                      3

Can this be done?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vikas GargAssociate Principal EngineerCommented:
You can use Row_Number function

Row_Number () over (order by your column with text data)

then you will not need to udpate
alexkingAuthor Commented:
I actually need to update the field - they are all set to zero currently and it needs to be updated with a sequntial number, alphabetically.
Jim HornMicrosoft SQL Server Data DudeCommented:
To illustrate, copy-paste the below T-SQL into SSMS and execute
-- Create a temp table just to illustrate
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
   DROP TABLE #tmp

CREATE TABLE #tmp (name varchar(50)) 

-- Create the test table
INSERT INTO #tmp (name) 
VALUES ('cat toys large'), ('dog toys small'),('cat toys medium'),('hamster wheels'), ('Dog chews')

-- Return a set with the ranking column, don't actually change the table
SELECT name, ROW_NUMBER() OVER (ORDER BY name) as rank_order
FROM #tmp

-- Change the table to include this number
ADD rank_order int 

SET rank_order = ro.rank_order 
FROM #tmp
   JOIN (SELECT name, ROW_NUMBER() OVER (ORDER BY name) as rank_order FROM #tmp) ro ON #tmp.name = ro.name


Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Deepak ChauhanSQL Server DBACommented:
You can use this query to update the table. replace actual column and table name.

update <tablename> set id=t.rno from (select ROW_NUMBER() over(order by name) as rno, name, id from <table anme>)t
where ty.name=t.name
Vikas GargAssociate Principal EngineerCommented:
Hi Update using row_number
;With CTE as
select *,Row_Number () over (order by your column with text data) rn from table
update a
set a.SequentialCode = b.rn
from table
inner join CTE b
on a.textcolumnname = b.textcolumnname 

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
alexkingAuthor Commented:
This method worked a treat - i did have some problems with some of the others. Thank you for the help! I have not used CTEs before - they are very useful!
Jim HornMicrosoft SQL Server Data DudeCommented:
alexking - Let me know what problems you had with mine, as it looked pretty good when I wrote it and matched what I understood were your requirements.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.