Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 806
Toby Avatar asked Sep 17 '10 14:09

Toby


2 Answers

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
like image 141
Fosco Avatar answered Nov 06 '22 03:11

Fosco


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
like image 43
Joe Stefanelli Avatar answered Nov 06 '22 01:11

Joe Stefanelli