How to Change Table and Stored Procedure Ownership in sql server

No.of Views1331
Bookmarked0 times
Downloads 
Votes0
By  dotnetfish   On  04 Oct 2010 10:10:28
Tag : Sql Servers , Database Administrator
How to Change Table and Stored Procedure Ownership in sql server
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this snippets help to you change the ownership for the table or stored procedures using T-SQL.

Script for change table ownership

DECLARE @old sysname, @new sysname, @sql varchar(1000) 

SET @old = 'oldOwner'
SET @new = 'dbo'
SET @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

change ownership for stored procedure

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

Hopes this helps.thank you reading.

 
Sign Up to vote for this article
 
About Author
 
dotnetfish
Occupation-
Company-
Member Type-Senior
Location-United States
Joined date-05 Sep 2010
Home Page-www.xininvoice.com
Blog Page-dotnetfish.blogspot.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top