2

My temporary table has a column holding a sequential numeric "row number".

How can I create a update this "row number" column when a record is deleted from the table?

Example

ID    Name    Row_Number
1     Jack    1
14    John    2
17    Bella   3

If I delete record with ID=14, I'd like record with ID=17 to be updated to be row_number 2

I've tried this:

SET @deletestr = ' DELETE FROM  ' + @tablename
        + ' where isnull(ltrim(rtrim([Row_Number])),0)=isnull(ltrim(rtrim(@originalRow_Number)),0)'
Paul Ellery
  • 1,615
  • 5
  • 17
  • 31
Bishoy Ezzat
  • 99
  • 10

3 Answers3

0

You could try something like the below, after the record is deleted, to renumber the table.

UPDATE x
SET x.row_number = x.new_row_number
FROM ( 
    SELECT ROW_NUMBER() OVER (Order by Id) AS new_row_number, row_number    
    FROM @tableName
) x
Paul Ellery
  • 1,615
  • 5
  • 17
  • 31
0
SET @deletestr = ' DELETE FROM  ' + @tablename
            + ' where isnull(ltrim(rtrim([Row_Number])),0)=isnull(ltrim(rtrim(@originalRow_Number)),0)'
JochenJung
  • 7,183
  • 12
  • 64
  • 113
kno kno
  • 1
  • 1
0

I recommend you don't bother, because row numbers are easy to derive and a nuisance to maintain.

Any SQL solution to your question will involve a self-join, because that's the way to find the next lowest value. By producing your row number with a Select, you save yourself some work and the server the overhead of updating the column.

James K. Lowden
  • 7,574
  • 1
  • 16
  • 31