I have a database that contains information about lectures. I needed to do some work to this, including renaming the primary key field, which is an identity. Having read up about this, it seemed straightforward enough, and I did the changes.
Afterwards, I found out that SQL Server had renumbered all of the IDs, filling in the gaps. However, it hadn't updated the other tables that had foreign key relations with this table, resulting in my data becoming totally corrupt.
For example, here is a sample of the data from before the change (old stuff, from the early days)...
As you can see, we don't have a lecture with an ID of 10. Note that the ID in the picture above is "ID" which is the new name, as I was trying to reproduce the problem on a restored backup.
After I renamed the primary key, SQL Server renumbered the lectures, closing up the gaps. You can see the results of the same query here...
See how we now have a lecture with ID 10? If you look at the other two fields shown here, it's renumbered them. This happened all the way through the table, so by the time we got to lecture with ID 2788 (fairly recent), it had been renumbered to 2760.
This happened on a couple of tables, and as you can imagine, has completely screwed up the entire database.
Anyone any idea how or why this happened? My first thought was that because I had renamed the primary key, which required SQL Server to drop and recreate the table, it had renumbered the IDs sequentially when reinserting the data. However, apart from the sheer stupidity of that idea, I couldn't reproduce it. I have renamed the primary key on the lectures table on the restored backup several times, and the numbering has not been affected. None of the other changes I did were remotely connected. They were just adding new columns, or of the type of changing varchar(1000) to varchar(max).
Using SQL Server 2012 if it makes any difference. I really need to know how and why this happened, as I still need to make the changes. We've lost a few days' worth of data, as we didn't spot this problem straight away. I don't want that to happen again.
Thanks for any help you can give.
FREE custom controls for Lightswitch! A collection of useful controls for Lightswitch developers. Download from the Visual Studio Gallery.
If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies athttp://dotnetwhatnot.pixata.co.uk/