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
UPDATE
  AnalysisTable
SET
  @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
                                        SequentialCode
cat toys large                  1
dog toys small                4
cat toys medium             2
hamster wheels            5
Dog chews                      3

Can this be done?
alexkingAsked:
Who is Participating?
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 GargBusiness Intelligence DeveloperCommented:
You can use Row_Number function

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

then you will not need to udpate
0
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.
0
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
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
GO

CREATE TABLE #tmp (name varchar(50)) 
GO

-- 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
ALTER TABLE #tmp
ADD rank_order int 
GO

UPDATE #tmp
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

SELECT * FROM #tmp

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

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
0
Vikas GargBusiness Intelligence DeveloperCommented:
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

0

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!
0
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
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.
0
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.