Change the Owner for Stored Procedures

This one comes from Tim Page, if you ever need to change the owner of several Store Procedures at the same time then this is the T-SQL for you. And this even supports SQL Sever 2005.

DECLARE
  @OldOwner sysname,
  @NewOwner sysname

 SET @OldOwner = 'oldOwner'
 SET @NewOwner = 'dbo'

DECLARE CURS CURSOR FOR
SELECT
  name
FROM
 sysobjects
WHERE
  type = 'p' 
AND
  uid = (SELECT uid FROM sysusers WHERE name = @OldOwner) 
AND 
  NOT name LIKE 'dt%' FOR READ ONLY

DECLARE @ProcName sysname

OPEN CURS

FETCH CURS INTO @ProcName

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @@VERSION >= 'Microsoft SQL Server 2005'
    BEGIN
        EXEC('alter schema ' + @NewOwner + ' transfer ' + @OldOwner + '.' + @ProcName)
        exec('alter authorization on ' + @NewOwner + '.' + @ProcName + ' to schema owner')
    END
    ELSE
        EXEC('sp_changeobjectowner ''' + @OldOwner + '.' + @ProcName + ''', ''' + @NewOwner + '''')

    FETCH CURS INTO @ProcName
END

CLOSE CURS
DEALLOCATE CURS
Author Greg Duffield

Greg has too many years experience in developement from VB for DOS all the way through to Windows Workflow and LINQ while covering pretty much every technology in between. A complete MS evangelist he is now Director of the only MS Gold Partner IT services company in Norfolk. Wehere they are producing Web 2 Applications for various sectors, and are currently entering the Haulage industry with their latest product.

Comments

Paul Marshall said:

Also, you could do away with the CURSOR.. see here : http://www.geekzilla.co.uk/View2356DC3A-9F53-4A95-9849-C4518B8E1F92.htm

14/Sep/2006 15:50 PM

Serno said:

Thanks a lot!!!!!

03/Dec/2007 22:02 PM

Arturo said:

Hey man, thank you for sharing this code, I was looking too hard for something like this, it worked great.

Thanks

17/May/2008 16:13 PM

David said:

You have just saved me lots of time with this code thanks

29/May/2008 10:08 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.