Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL update a column that lost order?

Tags:

c#

sql

I have a situation and I am weak at SQL. Here it is.

I have archived items, that are stored with a number. It is like this in the database table.

RowId   Number  CaseId
234        1       787
235        2       787
236        3       787
237        4       787
238        5       787

This is how it looks when first inserted. But after deleting, take Number 3 is deleted, It is now like this on DB.

RowId   Number  CaseId
234        1       787
235        2       787   
237        4       787
238        5       787

3 is gone but what I need is this.

RowId   Number  CaseId
234        1       787
235        2       787   
237        3       787
238        4       787

The numbers should be updated too. But I can't figure out a way to do this. By the way, there are many CaseId's. I won't update the whole table, I will select it by a CaseId. Can you tell me how to do this? I am using C# .NET

Should I take them in to a list (the way they are ordered from Select query) and check one by one and then update them? I can write the check one by one on C# but I think it won't be efficient. What is an efficient way to do this?

like image 717
Ada Avatar asked Oct 10 '12 11:10

Ada


1 Answers

Does Number have to be updated in the database itself? If not, do you even need to store this? Also are you writing SQL queries? Or just using Entity Framework? If you are writing actual queries, and if you just want the row number when you select the data back you can try something like:

SELECT RowId, ROW_NUMBER() OVER (ORDER BY RowId ASC) AS [Number], CaseId 
FROM [MyTable] 
WHERE CaseID = 787

EDIT: As pointed out by @Mike in the comments, it would probably make sense to make a view out of this. You can remove [Number] from the primary table and make a view like:

CREATE VIEW dbo.MyView 
AS 
    SELECT RowId, 
    ROW_NUMBER() OVER (PARTITION BY CaseId ORDER BY RowId ASC) AS Number, 
    CaseId FROM MyTable

The PARTITION statement will make sure that Number resets for every distinct RowId

like image 84
dbattaglia Avatar answered Sep 20 '22 09:09

dbattaglia