Changing a table owner

前端 未结 5 1255
名媛妹妹
名媛妹妹 2021-02-04 00:21

I\'m trying to change the owner of a table:

sp_changeobjectowner \'OWNER.TABLENAME\', \'dbo\'

But when executing I get the error message:

相关标签:
5条回答
  • 2021-02-04 01:00

    The correct way to do this in SQL Server 2005 and up is to stop thinking about the prefix as an "owner." The sp_changeobjectowner procedure has been deprecated since SQL Server 2005, and you should instead be using schema DDL, e.g.:

    ALTER SCHEMA dbo TRANSFER [current_owner].tablename;
    

    To check the current "owner" (this may return multiple rows if you have more than one tablename in multiple schemas):

    SELECT s.name
      FROM sys.schemas AS s
      INNER JOIN sys.tables AS t
      ON s.[schema_id] = t.[schema_id]
      WHERE t.name = N'tablename';
    

    Also be sure that you spell the object correctly. In a case-sensitive collation, for example, TABLENAME and tablename are not the same object, and spelling it with InCorrEcT CaSe could also lead to this error.

    0 讨论(0)
  • 2021-02-04 01:07

    If dropping the table is an option, you can drop and recreate under the desired user. Just specify dbo in the create script. For example:

    USE [X]
    GO
    
    /****** Object:  Table [dbo].[TableName]    Script Date: 4/21/2014 1:26:37 PM ******/
    
    CREATE TABLE [dbo].[TableName](
        [Field1] [bigint] NOT NULL,
        [Field2] [nvarchar](50) NOT NULL,
        [Field3] [datetime] NOT NULL
    ) ON [PRIMARY]
    
    GO
    
    0 讨论(0)
  • 2021-02-04 01:08

    Your statement is correct:

    EXEC sp_changeobjectowner '<owner>.<tableName>', '<newOwner>' 
    

    If the error happend, try to check who is the current owner of the table:

    EXEC sp_table_privileges '<tableName>'  
    
    0 讨论(0)
  • 2021-02-04 01:20
    SELECT 'Exec sp_changeobjectowner ''<CURRENTOWNER>.' + name + ''',  ''dbo''  '  FROM sys.objects WHERE type IN ('U','P','V','FN')
    

    Apply Following Steps

    (1) Run Following Query on Sql Prompt (2) Copy The Result and Paste Again to New Sql Query and Again Execute

    This is Change owner of your Tables, Views, Stored Procedures and Functions

    0 讨论(0)
  • 2021-02-04 01:22

    To cover the case where a table exists within a constructed schema name like 'Common' (that is not related to a username), then it is the schema owner that needs to be changed.

    alter authorization on schema::Common TO dbo;
    

    That will change the objects within the schema to the specified owner 'dbo' and keep the table within 'Common'.

    To list schema owners:

    select db_name() as Db, 
           sch.name as SchemaName, 
           u.Name as Owner
      from sys.schemas sch
      join sys.sysusers u
        on u.uid = sch.principal_id;
    
    0 讨论(0)
提交回复
热议问题