Thursday, September 18, 2008

Changing the owner of tables

Taken from: http://weblogs.asp.net/owscott/archive/2004/01/30/65229.aspx

The below helps changing ownership of tables (not database. You can follow the same principle to change other types of objects). Please note running the below would could limit access to these tables.

DECLARE @old sysname, @new sysname, @sql varchar(1000)
SELECT
@old = 'OldOwner'
, @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

No comments: