I imported a bunch of tables from an old sql server (2000) to my 2008 database. All the imported tables are prefixed with my username, for example: jonathan.MovieData
USE MyDB;
GO
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
GO
Ref: ALTER SCHEMA
Way to do it for an individual thing:
alter schema dbo transfer jonathan.MovieData
Use this code if you want to change all tables, views, and procedures at once.
BEGIN
DECLARE @name NVARCHAR(MAX)
, @sql NVARCHAR(MAX)
, @oldSchema NVARCHAR(MAX) = 'MyOldSchema'
, @newSchema NVARCHAR(MAX) = 'dbo'
DECLARE objCursor CURSOR FOR
SELECT o.name
FROM sys.objects o
WHERE type IN ('P', 'U', 'V')
OPEN objCursor
FETCH NEXT FROM objCursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER SCHEMA '+ @newSchema +' TRANSFER '+ @oldSchema + '.' + @name
BEGIN TRY
exec(@sql)
PRINT 'Success: ' + @sql
END TRY
BEGIN CATCH
PRINT 'Error executing: ' + @sql
END CATCH
FETCH NEXT FROM objCursor INTO @name
END
CLOSE objCursor
DEALLOCATE objCursor
END
It will execute a code like this
ALTER SCHEMA dbo TRANSFER MyOldSchema.xx_GetUserInformation
I just posted this to a similar question: In sql server 2005, how do I change the "schema" of a table without losing any data?
A slight improvement to sAeid's excellent answer...
I added an exec to have this code self-execute, and I added a union at the top so that I could change the schema of both tables AND stored procedures:
DECLARE cursore CURSOR FOR
select specific_schema as 'schema', specific_name AS 'name'
FROM INFORMATION_SCHEMA.routines
WHERE specific_schema <> 'dbo'
UNION ALL
SELECT TABLE_SCHEMA AS 'schema', TABLE_NAME AS 'name'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA <> 'dbo'
DECLARE @schema sysname,
@tab sysname,
@sql varchar(500)
OPEN cursore
FETCH NEXT FROM cursore INTO @schema, @tab
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER SCHEMA dbo TRANSFER [' + @schema + '].[' + @tab +']'
PRINT @sql
exec (@sql)
FETCH NEXT FROM cursore INTO @schema, @tab
END
CLOSE cursore
DEALLOCATE cursore
I too had to restore a dbdump, and found that the schema wasn't dbo - I spent hours trying to get Sql Server management studio or visual studio data transfers to alter the destination schema... I ended up just running this against the restored dump on the new server to get things the way I wanted.
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
See ALTER SCHEMA.
Generalized Syntax:
ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName;
I had a similar issue but my schema had a backslash in it. In this case, include the brackets around the schema.
ALTER SCHEMA dbo TRANSFER [DOMAIN\jonathan].MovieData;