CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

Change all database object owners to DBO - now runs changeOwner for you

This SQL Server script comes to you courtesy of Geoff Appleby!

Change All Object Owners to a given account (usually dbo) if not already owned by the SA (change the @NewOwner variable to another username string if you don't want DBO to own everything):

 1 declare @ObjectName varchar(256)
 2 -- we are only interested in USER Objects
 3 -- not already owned by 'sa'
 4 -- we don't want keys and constrainst
 5 set @ObjectName = (
 6   select top 1 [name] from sysobjects
 7   where uid <> SUSER_SID('sa')
 8   and [type] in ('FN','IF','P','TF','U','V')
 9   )
10 declare @ObjectOwner varchar(256)
11 declare @ObjectFullName varchar(512)
12 declare @NewOwner varchar(256)
13   set @NewOwner = 'dbo'
14  
15   -- default to 'dbo' if null
16   set @NewOwner = isnull(@NewOwner, 'dbo')
17  
18 while @ObjectName is not null
19 begin
20   select @ObjectOwner = USER_NAME(uid) 
21     from sysobjects where [name] = @ObjectName
22   set @ObjectFullName = @ObjectOwner + '.' + @Objectname
23   PRINT 'Changing ownership of ''' + @Objectname + 
24     ''' from ''' + @ObjectOwner + ''' to ''' + 
25     @NewOwner + ''''
26   execute sp_changeobjectowner @ObjectFullName, @NewOwner
27   set @ObjectName = (select top 1 [name] from sysobjects
28     where uid <> SUSER_SID('sa') 
29     and [type] in ('FN','IF','P','TF','U','V'))
30 end
Update: Fixed formatting.

Published Mar 21 2005, 06:05 AM by darrell
Filed under:

Comments

Raymond Lewallen said:

The code above excludes DTS packages. If you also need to change the owner of a DTS package, you have to call sp_DTSReplaceOwner in the msdb database.

EXEC msdb.dbo.sp_DTSReplaceOwner 'Raymond', 'sa'
# March 21, 2005 6:12 AM

Darrell said:

Thanks Raymond!
# March 21, 2005 8:03 AM

Duraid said:

have you seen your blog in firefox?
# March 21, 2005 8:48 AM

Darrell said:

Duraid - yes, it looks even worse in IE. :) I'm working on it now.
# March 21, 2005 8:52 AM

Geoff Appleby said:

Just switch to the GnoWare skin. It was written by some intelligent guy somewhere... *grin* (shameless plug for myself, I know :)
# March 21, 2005 2:58 PM

RIO - Randektív Informatikai Oldal said:

&lt;p&gt;&amp;lt;ul&amp;gt;&amp;lt;li&amp;gt;&amp;lt;a href=&amp;quot;http://story.news.yahoo.com/news?tmpl=story&amp;amp;cid=562&amp;amp;ncid=738&amp;amp;e=6&amp;amp;u=/ap/20050323/ap_on_hi_te/yahoo_upgrades&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt;Yahoo is 1Gb-re emeli a mail-t&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;&amp;lt;li
# March 23, 2005 7:07 AM
Check out Devlicio.us!