Search code examples
sqlsql-serverssmssql-server-2000

SQL Server Enterprise Manager - Mass Delete of Tables and Changing Ownership of Tables


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!


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