Monday, February 28, 2011

How to Change Schema for Tables, Views and Stored Procedures

SELECT 'ALTER SCHEMA dbo TRANSFER ' + s.Name + '.' + o.Name
FROM sys.Objects o
INNER JOIN sys.Schemas s on o.schema_id = s.schema_id
WHERE s.Name = 'yourschema'    And (o.Type = 'U' Or o.Type = 'P' Or o.Type = 'V')

How to Change DB Owner for Tables , Views and Stored Procedures

declare @OldOwner varchar(100)
declare @NewOwner varchar(100)
set @OldOwner = 'ABC'
set @NewOwner = 'dbo'

--Tables--
select 'EXEC sp_changeobjectowner ''[' + table_schema + '].[' + table_name + ']'', ''' + @NewOwner + ''' '
from information_schema.TABLES
where Table_schema = @OldOwner

--Views--
select 'EXEC sp_changeobjectowner ''[' + table_schema + '].[' + table_name + ']'', ''' + @NewOwner + ''' '
from information_schema.VIEWS
where Table_schema = @OldOwner

--Stored Procedures--
select 'EXEC sp_changeobjectowner ''[' + @OldOwner + '].[' + obj.name + ']'', ''' + @NewOwner + ''' '
from Sys.objects obj
Inner join Sys.schemas sch ON obj.schema_id=sch.schema_id
where [type]='P' AND is_ms_shipped=0 AND sch.[name] = @OldOwner