更改sql server表所有者

–执行这个语句,就可以把当前库的所有表的所有者改为dbo
exec sp_msforeachtable ‘sp_changeobjectowner ”?”, ”dbo”’

–如果是要用户表/存储过程/视图/触发器/自定义函数一齐改,则用游标(不要理会错误提示)
declare tb cursor local for
select ‘sp_changeobjectowner ”[‘+replace(user_name(uid),’]’,’]]’)+’].[‘
+replace(name,’]’,’]]’)+’]”,”dbo”’
from sysobjects
where xtype in(‘U’,’V’,’P’,’TR’,’FN’,’IF’,’TF’) and status>=0
open tb
declare @s nvarchar(4000)
fetch tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch tb into @s
end
close tb
deallocate tb
go

另:
–功能说明:成批更改数据库所有者的对象
–作者:不详
–用法:exec ChangeObjectOwner ‘nmkspro’,’dbo’
–即可将所有nmkspro所有者的对象改为dbo所有
–运行成功后将提示:”注意: 更改对象名的任一部分都可能破坏脚本和存储过程。”
CREATE PROCEDURE dbo.ChangeObjectOwner
@OldOwner as NVARCHAR(128),–参数原所有者
@NewOwner as NVARCHAR(128)–参数新所有者
AS

DECLARE @Name as NVARCHAR(128)
DECLARE @Owner as NVARCHAR(128)
DECLARE @OwnerName as NVARCHAR(128)

DECLARE curObject CURSOR FOR
select ‘Name’ = name,
‘Owner’ = user_name(uid)
from sysobjects
where user_name(uid)[email protected]
order by name

OPEN curObject
FETCH NEXT FROM curObject INTO @Name, @Owner
WHILE(@@FETCH_STATUS=0)
BEGIN
if @[email protected]
begin
set @OwnerName = @OldOwner + ‘.’ + rtrim(@Name)
exec sp_changeobjectowner @OwnerName, @NewOwner
end

FETCH NEXT FROM curObject INTO @Name, @Owner
END

close curObject
deallocate curObject
GO