[This is a bit of an unusual problem, I know…]
What I need is a script that will change every unique id value to new one in our database. The problem is that we have configuration tables that can be exported between instances of our software which is id-sensitive (clobbering existing ids). Years ago, we set up a "wide-enough" id gap between our development "standard configuration" and our client’s instances, which is now not wide enough 🙁 – e.g. we’re getting id conflicts when clients import our standard configuration.
A SQL script to do the following is definitely the simplest/shortest-timeframe thing that we can do. e.g. fixing the code is far too complicated and error prone to consider. Note that we are not "eliminating" the problem here. Just changing the gap from 1000’s to 1000000’s or more (the existing gap took 5 years to fill).
I believe the simplest solution would be to:
- change all our tables to UPDATE_CASCADE (none of them are – this will greatly simplify the script)
- create an identity table with the new lowest id that we want
- For each table, modify the id to the next one in the identity table (using identity insert modifier flags where necessary). Perhaps after each table is processed, we could reset the identity table.
- turn off UPDATE_CASCADE, and delete the identity table.
I am seeking any (partial or full) scripts for this.
Here we go with the code for SQL 2005. It’s huge, it’s hacky, but it will work (except in the case where you have a primary key that is a composite of two other primary keys).
If someone can re-write this with MrTelly’s faster id addition (which wouldn’t require building sql from a cursor for each updated row), then I’ll mark that as the accepted answer. (If I don’t notice the new answer, upvote this – then I’ll notice :))