SQL Server how to drop identity from a column

前端 未结 3 1723
予麋鹿
予麋鹿 2020-12-08 01:18

Is there an easy way to remove an identity from a table in SQL Server 2005?

When I use Management Studio, it generates a script that creates a mirror table without

相关标签:
3条回答
  • 2020-12-08 01:54

    I don't believe you can directly drop the IDENTITY part of the column. Your best bet is probably to:

    • add another non-identity column to the table
    • copy the identity values to that column
    • drop the original identity column
    • rename the new column to replace the original column

    If the identity column is part of a key or other constraint, you will need to drop those constraints and re-create them after the above operations are complete.

    0 讨论(0)
  • 2020-12-08 02:02

    You could add a column to the table that is not an identity column, copy the data, drop the original column, and rename the new column to the old column and recreate the indexes.

    Here is a link that shows an example. Still not a simple alter, but it is certainly better than 5231 lines.

    0 讨论(0)
  • 2020-12-08 02:07

    If you are on SQL Server 2005 or later, you can do this as a simple metadata change (NB: doesn't require an edition supporting partitioning as I originally stated).

    Example code pilfered shamelessly from the workaround by Paul White on this Microsoft Connect Item.

    USE tempdb;
    GO
    -- A table with an identity column
    CREATE TABLE dbo.Source 
    (row_id INTEGER IDENTITY PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
    GO
    -- Some sample data
    INSERT dbo.Source (data)
    VALUES (CONVERT(SQL_VARIANT, 4)),
            (CONVERT(SQL_VARIANT, 'X')),
            (CONVERT(SQL_VARIANT, {d '2009-11-07'})),
            (CONVERT(SQL_VARIANT, N'áéíóú'));
    GO
    -- Remove the identity property
    BEGIN TRY;
        -- All or nothing
        BEGIN TRANSACTION;
    
        -- A table with the same structure as the one with the identity column,
        -- but without the identity property
        CREATE TABLE dbo.Destination 
        (row_id INTEGER PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
    
        -- Metadata switch
        ALTER TABLE dbo.Source SWITCH TO dbo.Destination;
    
        -- Drop the old object, which now contains no data
        DROP TABLE dbo.Source;
    
        -- Rename the new object to make it look like the old one
        EXECUTE sp_rename N'dbo.Destination', N'Source', 'OBJECT';
    
        -- Success
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- Bugger!
        IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
        PRINT ERROR_MESSAGE();
    END CATCH;
    GO
    
    -- Test the the identity property has indeed gone
    INSERT dbo.Source (row_id, data)
    VALUES (5, CONVERT(SQL_VARIANT, N'This works!'))
    
    SELECT row_id,
            data
    FROM    dbo.Source;
    GO
    
    -- Tidy up
    DROP TABLE dbo.Source;
    
    0 讨论(0)
提交回复
热议问题