Change Schema Name Of Table In SQL

后端 未结 10 2246
清歌不尽
清歌不尽 2020-12-04 06:15

I want to change schema name of table Employees in Database. In the current table Employees database schema name is dbo I want to chan

相关标签:
10条回答
  • 2020-12-04 06:43

    Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:

    exec sp_rename 'Nameofobject', 'ReNameofobject'
    
    0 讨论(0)
  • 2020-12-04 06:44

    Check out MSDN...

    CREATE SCHEMA: http://msdn.microsoft.com/en-us/library/ms189462.aspx

    Then

    ALTER SCHEMA: http://msdn.microsoft.com/en-us/library/ms173423.aspx

    Or you can check it on on SO...

    How do I move a table into a schema in T-SQL

    0 讨论(0)
  • 2020-12-04 06:44

    Make sure you're in the right database context in SSMS. Got the same error as you, but I knew the schema already existed. Didn't realize I was in 'MASTER' context. ALTER worked after I changed context to my database.

    0 讨论(0)
  • 2020-12-04 06:50

    Create Schema :

    IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe')) 
    BEGIN
        EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
    END
    

    ALTER Schema :

    ALTER SCHEMA exe 
        TRANSFER dbo.Employees
    
    0 讨论(0)
  • 2020-12-04 06:50

    Try below

    declare @sql varchar(8000), @table varchar(1000), @oldschema varchar(1000), @newschema   varchar(1000)
    
      set @oldschema = 'dbo'
      set @newschema = 'exe'
    
     while exists(select * from sys.tables where schema_name(schema_id) = @oldschema)
    
      begin
          select @table = name from sys.tables 
          where object_id in(select min(object_id) from sys.tables where  schema_name(schema_id)  = @oldschema)
    
        set @sql = 'alter schema ' + @newschema + ' transfer ' + @oldschema + '.' + @table
    
       exec(@sql)
     end
    
    0 讨论(0)
  • 2020-12-04 06:55
    ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
    

    I always have to use the brackets when I use the ALTER SCHEMA query in SQL, or I get an error message.

    0 讨论(0)
提交回复
热议问题