Agent Jobs

How To Transfer Object Ownership Across All Tables

Suppose you’re doing yet another database migration and find yourself again changing the Object Ownership aka Schema Ownership in the post 2012 world… Here’s some quick logic to transfer all object ownership to DBO. Alternatively you can simply change ‘dbo’ to another name, but for the moment; we’ll be using DBO in this example.

use mydatabase;
set nocount on

declare @set_new_schema  varchar(max)
set     @set_new_schema  = ''
select  @set_new_schema  = @set_new_schema +
'alter schema dbo transfer ' + table_schema + '.' + table_name + '';' char(10)
from information_schema.tables where table_schema = 'MyOldUserName'

exec    (@set_new_schema)

Next just run a quick query to confirm.

select table_schema, table_name from information_schema.tables order by table_schema asc

If you’re looking to see whats statements are being run first; just run the following:

set nocount on

declare @set_new_schema  varchar(max)
set     @set_new_schema  = ''
select  @set_new_schema  = @set_new_schema +
'alter schema dbo transfer ' + table_schema + '.' + table_name + '';' char(10)
from information_schema.tables where table_schema = 'MyOldUserName'

select    (@set_new_schema) for xml path(''), type

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s