How can I change primary key on SQL Azure

前端 未结 5 1579
无人共我
无人共我 2021-02-07 04:44

I am going to change the primary key on SQL Azure. But it throws an error when using Microsoft SQL Server Management Studio to generate the scripts. Because every tables on SQL

相关标签:
5条回答
  • 2021-02-07 05:03

    I appreciate that this may be late in the day for yourself, but it may help others.

    I recently came across this issue and found the least painful solution was to download the database from Azure, restore it locally, update the primary key locally (as the key constraint is a SQL Azure specific issue), and then restore the database back into Azure.

    This saved any issues in regards to renaming databases or transferring data between them.

    0 讨论(0)
  • 2021-02-07 05:24

    This question is outdated because changing PK is already supported in latest version of SQL Azure. And you don't have to create temporary table.

    0 讨论(0)
  • 2021-02-07 05:27

    You can try the following scripts. Change it to suit for your table def.

    EXECUTE sp_rename N'[PK_MyTable]', N'[PK_MyTable_old]',  'OBJECT'
    
    CREATE TABLE [dbo].[Temp_MyTable](
    [id] [int] NOT NULL,
    [text] [text] NOT NULL CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED (
    [id] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON))
    
    INSERT INTO dbo.[Temp_MyTable] (Id, Text)
    SELECT Id, Text FROM dbo.MyTable
    
    drop table dbo.MyTable
    EXECUTE sp_rename N'Temp_MyTable', N'MyTable', 'OBJECT'
    
    0 讨论(0)
  • 2021-02-07 05:28

    upgrade SQL V12 and heaps are supported on it. So you can drop the primary key and recreate it.

    0 讨论(0)
  • 2021-02-07 05:29

    I ran into this exact problem and contacted the Azure team on the forums. Basically it isn't possible. You'll need to create a new table and transfer the data to it.

    What I did was create a transaction and within it do the following:

    • Renamed the old table to OLD_MyTable.

    • Create the new table with the correct Primary Key and call it MyTable.

    • Select the contents from OLD_MyTable into MyTable.

    • Drop OLD_MyTable.

    You may also need to call sp_rename on any constraints so they don't conflict.

    See also: http://social.msdn.microsoft.com/Forums/en/ssdsgetstarted/thread/5cc4b302-fa42-4c62-956a-bbf79dbbd040

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