Home Home    Forum    Blog    Feed your aggregator (RSS 2.0)

The Johnnynine Weblog - How to change the owner of all tables in a database
A weblog by Johnny Hughes
 
 Tuesday, July 12, 2005

I can’t tell you how many times I’ve done an import and ended up with the wrong database owner.  Use this following script to change the owner on all tables in a database.

In the sql below, set the @oldowner and @newowner variables appropriately.

DECLARE @oldowner sysname, @newowner sysname, @sql varchar(1000)

SELECT
  @oldowner = 'OLD_OWNER',
  @newowner = 'dbo',
  @sql = '
  IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
  WHERE
      QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
      AND TABLE_SCHEMA = ''' + @oldowner + '''
  )
  EXECUTE sp_changeobjectowner ''?'', ''' + @newowner + ''''

EXECUTE sp_MSforeachtable @sql

(I found this somewhere on the internet some time ago but have lost it's reference.)

Tuesday, July 12, 2005 5:09:15 PM (US Mountain Standard Time, UTC-07:00)  #    Comments [0]   Database | Sql Server  | 
Copyright © 2009 Johnny Hughes. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.