Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I have two schema. Schema1 and Schema2

How would I transfer all the tables from schema1 to schema2?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Execute this for all of the tables:

alter schema2
transfer schema1.table1;

To programmatically get the statements to execute:

declare
    @SourceSchemaName sysname,
    @DestinationSchemaName sysname,
    @AlterStatements varchar(max);

set @SourceSchemaName = 'NewSchema';
set @DestinationSchemaName = 'HumanResources';
set @AlterStatements = '';

select
    @AlterStatements +=
        'alter schema ' + quotename(@DestinationSchemaName) + 
        ' transfer ' + quotename(schema_name(schema_id)) + '.' + quotename(object_name(object_id)) +
        char(13) + char(10)
from sys.tables
where schema_id = schema_id(@SourceSchemaName);

print @AlterStatements;
share|improve this answer
    
I have a thousand tables. –  Emman Bangis Jul 9 at 18:46
2  
I edited my answer to show code to generate the ALTER statements. –  Thomas Stringer Jul 9 at 18:46

Assuming destination schema is empty:

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'
ALTER SCHEMA Schema2 TRANSFER Schema1.' 
  + QUOTENAME(t.name) + ';' FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'Schema1';

PRINT @sql;
-- EXEC sp_executesql @sql;

If the destination schema is not empty, you'll need additional handling for conflicts.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.