We currently have multiple databases but would like to combine them and, instead, separate our domain contexts using schemas.
In MS SQL Server 2008 R2, how can I relocate all the contents of one schema into another in bulk?
For example, all of the tables, views, procedures, indices, etc… that we created into the dbo
schema will now live in the foo
schema.
EDIT: I wanted to clarify based on AaronBertrand's great comments. This is not a multi-tenancy situation. Our situation is where internal tools plugins were developed in isolation by developers who didn't merge their tables into the tool's database.
Best Answer
The basic concept is actually quite simple: you generate a script from
sys.objects
andsys.schemas
that buildsALTER SCHEMA TRANSFER
statements. So for example, you have three objects in thedbo
schema, and you want to move all of them to theblat
schema:The following code:
Will yield this script (but perhaps not in this order):
(You may want to add additional filters to leave out objects in the
dbo
schema that you don't want to move, leave out certain object types (e.g. maybe all of your functions are utility functions and don't need to move), generate the script ordered by object type, etc.)But there are a couple of problems with moving all of your objects to a new schema:
Probably a lot your code will still reference these objects as
dbo.object
- there is no easy way to fix this except brute force. You can probably find all of the occurrences ofdbo.
pretty easily, but these can also return false positives, such asEXEC dbo.sp_executesql
,dbo.
in comments, true references to objects that remain in thedbo.
schema, etc.Your dependencies will probably be completely out of whack, but I haven't thoroughly tested this. I do know that in this scenario:
The foreign keys actually migrate more smoothly than I expected (with the caveat that I'm testing on a much more recent version than you). But because the code in
blat.pX
still referencesdbo.bar
, obviously executing the procedure:Is going to yield this error:
And dependency queries, such as:
Will yield this error:
And querying the view:
Yields these errors:
So, this could involve a lot of cleanup. And after you've fixed all the object references, you'll probably want to recompile all of the modules and refresh all of the views in the new schema. You can generate a script for that quite similar to the example above.