How do I change db schema to dbo

前端 未结 11 2502
无人共我
无人共我 2020-12-02 05:38

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

11条回答
  •  长情又很酷
    2020-12-02 05:55

    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.

提交回复
热议问题