Skip to content

Move Tables to a New Schema (Rename Schema)

In SQL, you cannot rename a schema, so we need to move the tables.

Proceed like this:

  1. create new schema

    CREATE SCHEMA bc_tbd;
    

  2. prepare the script, adding the names of the schemas, and excluding tables you do not want to move (e.g. history tables)

    -- Move all objects from the old schema to the new schema
    DECLARE @OldSchemaName sysname = 'bc';
    DECLARE @NewSchemaName sysname = 'bc_tbd';
    DECLARE @sql NVARCHAR(MAX) = N'';
    
    SELECT @sql += N'ALTER SCHEMA ' + QUOTENAME(@NewSchemaName) 
        + N' TRANSFER ' + QUOTENAME(s.name) + N'.' + QUOTENAME(o.name) + N';'
        + CHAR(13) + CHAR(10)
    FROM sys.objects AS o
    INNER JOIN sys.schemas AS s
    ON o.[schema_id] = s.[schema_id]
    WHERE s.name = @OldSchemaName
    AND o.name NOT IN ('FactuurDetails_hist', 'History'); -- OR: Exclude certain tables
    
    EXEC sp_executesql @sql;
    

You might get an error like this:

Started executing query at Line 1
Msg 15151, Level 16, State 1, Line 10
Cannot find the object 'PK_timesheets', because it does not exist or you do not have permission.
Total execution time: 00:00:00.457

You can ignore it (or post a fix here).