How to Change Schema of MS SQL Tables, Stored Procedures, and Views All at the Same Time

Sometimes changing database users changes who the database owner is for a table from dbo.tablename to badschema.tablename. This will also affect any stored procedures created under the tables with the incorect schema.  If you need to change the schema for these tables back to the default dbo schema follow the steps below.

Part 1

  1. Open Microsoft SQL Server Management Studio and log in.
  2. Click the New Query button.
  3. Paste the following script into the New Query box changing oldschema to the name of the current schema:
    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 'oldschema'  //(old user name)
    And (o.Type = 'U' Or o.Type = 'P' Or o.Type = 'V')
  4. Click Execute

This query will result in output in the Results box which looks similar to the output below:

ALTER SCHEMA dbo TRANSFER yourschema.Table1
ALTER SCHEMA dbo TRANSFER yourschema.Table2
ALTER SCHEMA dbo TRANSFER yourschema.Table3
ALTER SCHEMA dbo TRANSFER yourschema.Table4
ALTER SCHEMA dbo TRANSFER yourschema.Table5
ALTER SCHEMA dbo TRANSFER yourschema.Table6

Part 2

  1. Click the New Query button.
  2. Paste the queries from the output of Part 1 into your new Query box
  3. Click Execute
Advertisements
Leave a comment

Leave your opinion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: