How to rename a table in SQL Server?

后端 未结 8 1098
忘了有多久
忘了有多久 2020-12-12 10:10

The SQL query that I have used is :

ALTER TABLE oldtable RENAME TO newtable;

But, it gives me an error.

相关标签:
8条回答
  • 2020-12-12 10:44

    When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too

    I took a code example for table dependencies at Pinal Dave's blog here

    USE AdventureWorks
    GO
    SELECT
    referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
    referencing_object_name = o.name,
    referencing_object_type_desc = o.type_desc,
    referenced_schema_name,
    referenced_object_name = referenced_entity_name,
    referenced_object_type_desc = o1.type_desc,
    referenced_server_name, referenced_database_name
    --,sed.* -- Uncomment for all the columns
    FROM
    sys.sql_expression_dependencies sed
    INNER JOIN
    sys.objects o ON sed.referencing_id = o.[object_id]
    LEFT OUTER JOIN
    sys.objects o1 ON sed.referenced_id = o1.[object_id]
    WHERE
    referenced_entity_name = 'Customer'
    

    So, all these dependent objects needs to be updated also

    Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too

    0 讨论(0)
  • 2020-12-12 10:46

    This is what I use:

    EXEC sp_rename 'MyTable', 'MyTableNewName';
    
    0 讨论(0)
  • 2020-12-12 10:48

    To rename a column:

    sp_rename 'table_name.old_column_name', 'new_column_name' , 'COLUMN';
    

    To rename a table:

    sp_rename 'old_table_name','new_table_name';
    
    0 讨论(0)
  • 2020-12-12 10:51

    To change a table name with a different schema:

    Example: Change dbo.MyTable1 to wrk.MyTable2

    EXEC SP_RENAME 'dbo.MyTable1', 'MyTable2'
    
    ALTER SCHEMA wrk TRANSFER dbo.MyTable2
    
    0 讨论(0)
  • 2020-12-12 10:53

    To rename a table in SQL Server, use the sp_rename command:

    exec sp_rename 'schema.old_table_name', 'new_table_name'
    
    0 讨论(0)
  • 2020-12-12 10:58

    Nothing worked from proposed here .. So just pored the data into new table

    SELECT * 
    INTO [acecodetable].['PSCLineReason']
    FROM [acecodetable].['15_PSCLineReason'];
    

    maybe will be useful for someone..

    In my case it didn't recognize the new schema also the dbo was the owner..

    UPDATE

    EXECUTE sp_rename N'[acecodetable].[''TradeAgreementClaim'']', N'TradeAgreementClaim';
    

    Worked for me. I found it from the script generated automatically when updating the PK for one of the tables. This way it recognized the new schema as well..

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