I want to move a table into a specific Schema using T-SQL? I am using SQL Server 2008.
2 Answers
ALTER SCHEMA TargetSchema
TRANSFER SourceSchema.TableName;
If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable
stored procedure:
exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"
Ref.: ALTER SCHEMA
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
-
1Why the downvote for my correct answer? Please check mine against the accepted answer, which is the same, and has 257 upvotes already (including mine). Jan 20, 2016 at 11:55
-
2Have an upvote for confirming the data remains intact, which just saved my blood pressure... :)– user593806Feb 7, 2016 at 23:05
-
10@DaveBoltnman: you've entered an answer 6 years after the accepted answer and by your own comment above "which is the same" . Oct 13, 2016 at 7:47
-
4why wouldn't data in a table stay intact just because the table is moved into a different schema container? Oct 15, 2016 at 2:02
-
4nice name change @DaveBoltman. Answering old questions is great, when they add something to existing answers. Jul 18, 2019 at 9:21