vendredi 19 février 2016

Renumbering _IDs for some rows in SQLite database (Android)

Say, I have a table MYTABLE with _ID defined (INTEGER PRIMARY KEY AUTOINCREMENT) like the one below: (_ID, OTHER):

1, AAA

2, BBB

3, CCC

I want it to be like this (2, XXX is a new inserted row):

1, AAA

2, XXX

3, BBB

4, CCC

So, I want to renumber some rows _IDs to insert new row in beetwen, as in example:

  • renumber rows from 2 to TOP (increment their _IDs by 1),
  • insert new row with _ID = 2.

Second part is easy but there is a problem with the renumbering. If I use this command:

UPDATE MYTABLE SET _ID = (_ID + 1) WHERE _ID >= 2

I end up with an error. Obviously I am trying to break a constraint on _ID column for which all rows must have unique values. I think that trying to change _ID for second row (from 2 to 3) causes error (right?). I understand that I can't do that. So how to deal with this problem? I think I can't temporarily drop unique constraint on _ID column and then reenable it in SQLite? Is there a way to force SQLite engine to start renumbering from top row (3 in my example) instead of from the first one (2 in my example)? All I can think of is to do the renumbering twice:

  • first time change _IDs so that first changed _ID becomes one more that the last one and continue to the top row (2 becomes 4, 3 becomes 5)
  • then renumbering down should be easy (4 becomes 3, 5 becomes 4).
  • now _ID = 2 is free and I can insert new row with this _ID.

Is there any other way, more efficient and faster? I am referring to SQLite and Android.

Aucun commentaire:

Enregistrer un commentaire