views:

5528

answers:

7

I have a table that got into the "db_owner" schema, and I need it in the "dbo" schema.

Is there a script or command to run to switch it over?

+11  A: 

ALTER SCHEMA NewSchama TRANSFER dbo.Table1

Stephen Wrighton
+7  A: 

In SQL Server Management Studio:

  1. Right click the table and select modify
  2. On the properties panel choose the correct owning schema.
Jason Punyon
thanks, funny, if you just right click -> properties the schema is unchangeable, so I assumed it was one of those command only ninja tasks. Glad to know that its not as painful as it felt.
DevelopingChris
A: 

You need to firstly stop all connections to the database, change the ownership of the tables that are 'db_owner' by running the command

sp_MSforeachtable @command1="sp_changeobjectowner ""?"",'dbo'"

where ? is the table name.

Craig
+4  A: 

simple answer

sp_changeobjectowner [ @objname = ] 'object' , [ @newowner = ] 'owner'

you don't need to stop all connections to the database, this can be done on the fly.

Jeremy
+2  A: 

When I use SQL Management Studio I do not get the 'Modify' option, only 'Design' or 'Edit'. If you have Visual Studio (I have checked VS.NET 2003, 2005 & 2008) you can use the Server Explorer to change the schema. Right click on the table and select 'Design Table' (2008) or 'Open Table Definition' (2003, 2005). Highlight the complete "Column Name" column. You can then right click and select 'Property Pages' or Properties (2008). From the property sheet you should see the 'Owner' (2003 & 2005) or 'Schema' (2008) with a drop down list for possible schemas.

Anthony K
+3  A: 

Show all TABLE_SCHEMA by this select:

SELECT TABLE_SCHEMA, TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 

You can use this query to change all schema for all tables to dbo table schema:

DECLARE cursore CURSOR FOR 

SELECT TABLE_SCHEMA, TABLE_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     
 FETCH NEXT FROM cursore INTO @schema, @tab     
END 

CLOSE cursore     
DEALLOCATE cursore
sAeid mOhammad hAshem
A: 

Just Use This

ALTER SCHEMA dbo TRANSFER db_owner.Tablename

Suresh