Question

I have pretty much no experience with SQL Server's Enterprise Manager so I am not sure if this is even possible (or hopefully laughably simple!)

During an import into a database something has happened where each table has duplicated itself with two important differences.

The first is that the Owner on both tables is different, the second is that only the structure has copied across on one of the copies.

Sod's law indicated that of course the data was stored on the tables owned by the wrong person, so my question is can I quickly delete all tables owned by one user and can I quickly change the ownership of all other tables to bring them in line.

There are enough tables that automation is going to be my preferred option by a LONG way!

Any help would be greatly appreciated, I am running SQL Server 2000

Was it helpful?

Solution

declare @emptyOwner varchar(20)
declare @wrongOwner varchar(20)
declare @emptyOwnerID bigint
declare @wrongOwnerID bigint
declare @tableName nvarchar(255)

set @emptyOwner = 'dbo'
set @wrongOwner = 'guest'

select @emptyOwnerID = (select uid from sysusers where name = @emptyOwner)
select @wrongOwnerID = (select uid from sysusers where name = @wrongOwner)

select name as tableName
into #tempTable
from systables
where type='U'
and exists (select 1 from systables where type = 'U' and uid = @emptyOwnerID)
and exists (select 1 from systables where type = 'U' and uid = @wrongOwnerID)

declare @dynSQL nvarchar(MAX)

declare ownme cursor for
  select tableName from #tempTable

open ownme
fetch next from ownme into @tableName

while @@FETCH_STATUS = 0
begin
    @dynSQL = 'DROP TABLE [' + @emptyOwner + '].[' + @tableName + ']'
    exec(@dynSQL)

    @dynSQL = 'sp_changeobjectowner ''[' + @wrongOwner + '].[' + @tableName + ']'',''' + @emptyOwner + ''''
    exec(@dynSQL)

    fetch next from ownme into @tableName
end

close ownme
deallocate ownme

OTHER TIPS

For changing ownership, see: SQL Table Ownership Changes, Quick and Easy

The code given in the above link is:

DECLARE @old sysname, @new sysname, @sql varchar(1000)

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

EXECUTE sp_MSforeachtable @sql
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top