SQL Server企业管理器 - 批量删除表和更改表的所有权

时间:2010-09-17 14:31:23

标签: sql sql-server sql-server-2000 enterprise-manager

我对SQL Server的企业管理器几乎没有任何经验,所以我不确定这是否可能(或希望可笑的简单!)

在导入到数据库期间,发生了一些事情,其中​​每个表都有重复的两个重要区别。

第一个是两个表上的所有者不同,第二个是只有结构复制了其中一个副本。

Sod的法律表明,当然数据存储在错误的人拥有的表中,所以我的问题是我可以快速删除一个用户拥有的所有表,并且我可以快速更改所有其他表的所有权以带来它们在线。

有足够多的表格可以通过LONG方式将自动化作为我的首选方法!

我将非常感谢任何帮助,我正在运行SQL Server 2000

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

有关更改所有权的信息,请参阅:SQL Table Ownership Changes, Quick and Easy

上述链接中给出的代码是:

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